408

I need to replace every instance of '_' with a space, and every instance of '#' with nothing/empty.

var string = '#Please send_an_information_pack_to_the_following_address:';

I've tried this:

string.replace('#','').replace('_', ' ');

I don't really like chaining commands like this. Is there another way to do it in one?

4
  • See the answer to this question: stackoverflow.com/questions/7072330/…
    – DeweyOx
    May 16, 2013 at 0:14
  • I bet your future self will regret your decision, it's much clear to read chained commands than ugly regexes Feb 18, 2022 at 20:07
  • 1
    @EduardoMolteni I disagree - i think it's important to understand how regular expressions work, not to mention with the replace method to achieve my OQ you'd still require regular expressions as a chained option unless you create a custom prototype extension anyways Feb 20, 2022 at 21:26
  • 1
    @DeweyOx Read the OP it's not the answer, and it's been answered many times, don't litter old questions with incorrect answer please Mar 14, 2022 at 0:52

21 Answers 21

706

Use the OR operator (|):

var str = '#this #is__ __#a test###__';

console.log(
  str.replace(/#|_/g, '') // "this is a test"
)

You could also use a character class:

str.replace(/[#_]/g,'');

Fiddle

If you want to replace the hash with one thing and the underscore with another, then you will just have to chain

function allReplace(str, obj) {
  for (const x in obj) {
    str = str.replace(new RegExp(x, 'g'), obj[x]);
  }
  return str;
};


console.log(
  allReplace( 'abcd-abcd', { 'a': 'h', 'b': 'o' } ) // 'hocd-hocd'
);

Why not chain, though? I see nothing wrong with that.

14
  • 5
    This is cool, but I need to replace underscores with spaces not empty, can I do this? May 16, 2013 at 0:14
  • Thought so, but still you've helped me understand how replace expressions work a bit better :) May 16, 2013 at 0:19
  • Your prototype doesn't work? are you able to provide an example on fiddle, i keep getting errors May 16, 2013 at 0:43
  • 4
    Another option for #|_ is [#_], and you might as well use + to match any consecutive matches to improve performance
    – Ian
    May 16, 2013 at 1:08
  • 3
    Cool thanks ... if need replace blank spaces and another symbols str.replace(/[+ -]/g,''); just put blank space in the middle.
    – equiman
    May 5, 2016 at 14:40
146

If you want to replace multiple characters you can call the String.prototype.replace() with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping that you will use in that function.

For example, if you want a replaced with x, b with y, and c with z, you can do something like this:

const chars = {
  'a': 'x',
  'b': 'y',
  'c': 'z'
};

let s = '234abc567bbbbac';
s = s.replace(/[abc]/g, m => chars[m]);
console.log(s);

Output: 234xyz567yyyyxz

7
  • 8
    since you use ES6 (arrow function) you should also replace var with const here. an alternative for extended browser support: var s ='234abc567bbbbac'; s = s.replace(/[abc]/g, function(m) { return {'a':'x','b':'y','c':'z'}[m]; }); console.log(s); Mar 23, 2018 at 15:52
  • this is really good. thanks. What is the part where you used an object to do an or statement. do you have documentation or reference to something that explains that. Pretty good use case. May 1, 2020 at 22:03
  • 4
    You can replace many in one line: string.replace(/[#_]/g, x => ({'_': ' ', '#': ''})[x]); Note the () around the object — it will error without them.
    – wilcro
    Feb 26, 2021 at 18:11
  • @wilcro i think [x] should be inside parenthesis, ({'_': ' ', '#': ''}[x]) instead of ({'_': ' ', '#': ''})[x] .
    – Rubel
    Nov 16, 2021 at 7:08
  • @wilcro Nice, clear and compact - just what I needed. Jun 10, 2022 at 17:26
65

Chaining is cool, why dismiss it?

Anyway, here is another option in one replace:

string.replace(/#|_/g,function(match) {return (match=="#")?"":" ";})

The replace will choose "" if match=="#", " " if not.

[Update] For a more generic solution, you could store your replacement strings in an object:

var replaceChars={ "#":"" , "_":" " };
string.replace(/#|_/g,function(match) {return replaceChars[match];})
3
  • 7
    take it the extra step: var regex = new RegExp( Object.keys(replaceChars).join("|"), "g"); string.replace(regex,function(match) {return replaceChars[match];}) this makes modifying the replaceChars easier.
    – RozzA
    Aug 4, 2016 at 21:06
  • @RozzA thanks. Object.keys was not mainstream at the time.
    – Christophe
    Aug 6, 2016 at 5:44
  • I totally forgot about replacement function option for replace second parameter, for helping me remember :)
    – Luckylooke
    Apr 9, 2018 at 20:21
55

Specify the /g (global) flag on the regular expression to replace all matches instead of just the first:

string.replace(/_/g, ' ').replace(/#/g, '')

To replace one character with one thing and a different character with something else, you can't really get around needing two separate calls to replace. You can abstract it into a function as Doorknob did, though I would probably have it take an object with old/new as key/value pairs instead of a flat array.

1
11

I don't know if how much this will help but I wanted to remove <b> and </b> from my string

so I used

mystring.replace('<b>',' ').replace('</b>','');

so basically if you want a limited number of character to be reduced and don't waste time this will be useful.

8

Multiple substrings can be replaced with a simple regular expression. For example, we want to make the number (123) 456-7890 into 1234567890, we can do it as below.

var a = '(123) 456-7890';
var b = a.replace(/[() -]/g, '');
console.log(b); // results 1234567890

We can pass the substrings to be replaced between [] and the string to be used instead should be passed as the second parameter to the replace function.

7

Second Update

I have developed the following function to use in production, perhaps it can help someone else. It's basically a loop of the native's replaceAll Javascript function, it does not make use of regex:

function replaceMultiple(text, characters){
  for (const [i, each] of characters.entries()) {
    const previousChar = Object.keys(each);
    const newChar = Object.values(each);

    text = text.replaceAll(previousChar, newChar);
  }  
  
return text
}

Usage is very simple. Here's how it would look like using OP's example:


const text = '#Please send_an_information_pack_to_the_following_address:';
const characters = [
    {
    "#":""
    },
   {
    "_":" "
    },
]

const result = replaceMultiple(text, characters);

console.log(result); //'Please send an information pack to the following address:'

Update

You can now use replaceAll natively.

Outdated Answer

Here is another version using String Prototype. Enjoy!

String.prototype.replaceAll = function(obj) {
    let finalString = '';
    let word = this;
    for (let each of word){
        for (const o in obj){
            const value = obj[o];
            if (each == o){
                each = value;
            }
        }
        finalString += each;
    }
    
    return finalString;
};

'abc'.replaceAll({'a':'x', 'b':'y'}); //"xyc"
2
  • 2
    This is worst possible answer. You should not override function accepted in official spec by your own. tc39.es/ecma262/multipage/…
    – Daniel
    Jun 25, 2021 at 13:12
  • 1
    @Daniel You're correct. When I wrote this back in 2019 "replaceAll" wasn't yet available. Thanks for the heads up. Jun 26, 2021 at 2:59
6

You can just try this :

str.replace(/[.#]/g, 'replacechar');

this will replace .,- and # with your replacechar !

1
  • This answer has already been provided and doesn't handle replacing different characters with other characters, see OP. Sep 13, 2016 at 2:25
5

Please try:

  • replace multi string

    var str = "http://www.abc.xyz.com"; str = str.replace(/http:|www|.com/g, ''); //str is "//.abc.xyz"

  • replace multi chars

    var str = "a.b.c.d,e,f,g,h"; str = str.replace(/[.,]/g, ''); //str is "abcdefgh";

Good luck!

1
  • Best solution I found ! Mar 5, 2022 at 16:00
4

Here's a simple way to do it without RegEx.
You can prototype and/or cache things as desired.

// Example: translate( 'faded', 'abcdef', '123456' ) returns '61454'
function translate( s, sFrom, sTo ){
    for ( var out = '', i = 0; i < s.length; i++ ){
        out += sTo.charAt( sFrom.indexOf( s.charAt(i) ));
    }
    return out;
}
3
  • I know you didn't state it, but isn't it much more elegant to just use regex? str.replace(/#|_/g,'') May 6, 2015 at 2:53
  • 1
    @ShannonHochkins For sure! I don't mean to bash on RegEx; I'm just showing another option. RegEx isn't always intuitive and lends itself to be used "as a hammer, treating every problem as a nail". Plus looking at the other answers, as a reusable function this one isn't much more lengthy, and the parameters are easy to understand. Personally I'd go with a short RegEx for the question here, and it makes sense if you're just looking for a quick drop-in snippet that you don't mind not understanding completely.
    – Beejor
    May 11, 2015 at 20:35
  • 1
    Well, if you need to translate a characters (à la sed y command or à la Unix tr), this seems like the right answer.
    – Édouard
    May 27, 2016 at 13:17
3

You could also try this :

function replaceStr(str, find, replace) {
    for (var i = 0; i < find.length; i++) {
        str = str.replace(new RegExp(find[i], 'gi'), replace[i]);
    }
    return str;
}

var text = "#here_is_the_one#";
var find = ["#","_"];
var replace = ['',' '];
text = replaceStr(text, find, replace);
console.log(text);

find refers to the text to be found and replace to the text to be replaced with

This will be replacing case insensitive characters. To do otherway just change the Regex flags as required. Eg: for case sensitive replace :

new RegExp(find[i], 'g')
2

You can also pass a RegExp object to the replace method like

var regexUnderscore = new RegExp("_", "g"); //indicates global match
var regexHash = new RegExp("#", "g");

string.replace(regexHash, "").replace(regexUnderscore, " ");

Javascript RegExp

1
  • OP doesn't want to chain replace calls - this doesn't help avoid that.
    – Dennis
    May 16, 2013 at 0:19
2

yourstring = '#Please send_an_information_pack_to_the_following_address:';

replace '#' with '' and replace '_' with a space

var newstring1 = yourstring.split('#').join('');
var newstring2 = newstring1.split('_').join(' ');

newstring2 is your result

5
  • Your answer doesn't use a shred of jQuery, and also doesn't follow the OP, '#this #is__ #a test###'.split('_').join(' ') wouldn't work as you'd end up with more whitespace Nov 16, 2017 at 9:37
  • @ShannonHochkins How more white spaces will be added ? Nov 16, 2017 at 12:13
  • Have a look at my example, when there's an underscore before a space, or two underscores you'll end up with multiple spaces. Dec 5, 2017 at 22:02
  • @ShannonHochkins the questioner deals with the string '#Please send_an_information_pack_to_the_following_address:'; there is no space here. why i will think of it. when think, why only about space, many other things may happen. Jan 23, 2018 at 3:29
  • I suggest you re read the OP, I'm the original poster and you can see clearly in my first variable var str = '#this #is__ __#a test###__'; that there's cleary multiple spaces in this string. Feb 7, 2018 at 0:22
2

Here is a "safe HTML" function using a 'reduce' multiple replacement function (this function applies each replacement to the entire string, so dependencies among replacements are significant).

// Test:
document.write(SafeHTML('<div>\n\
    x</div>'));

function SafeHTML(str)
    {
    const replacements = [
        {'&':'&amp;'},
        {'<':'&lt;'},
        {'>':'&gt;'},
        {'"':'&quot;'},
        {"'":'&apos;'},
        {'`':'&grave;'},
        {'\n':'<br>'},
        {' ':'&nbsp;'}
        ];
    return replaceManyStr(replacements,str);
    } // HTMLToSafeHTML

function replaceManyStr(replacements,str)
    {
    return replacements.reduce((accum,t) => accum.replace(new RegExp(Object.keys(t)[0],'g'),t[Object.keys(t)[0]]),str);
    }
7
  • Thanks for the post, however it's quite extensive compared to the accepted answer Sep 9, 2019 at 4:49
  • The answer to the question is a one-line function. How is that "extensive"? Making user input safe is an important example. You are too critical. 'reduce' is a very useful technique that you should know about. Sep 9, 2019 at 11:37
  • I said your answer is too extensive, it's a lot more code, you're using regular expressions anyway, just making the process too convoluted, not sure how you think your answer is a reduction compared to any of these answers... Sep 9, 2019 at 22:50
  • My answer is a 'reduce' answer because it uses the Array.prototype.reduce function. A shorter answer might use a string instead of property keys, exploiting the fact that a "safe HTML" function works only on replacing single characters. I challenge you to come up with a more elegant answer instead of rudely complaining in public like this. Sep 10, 2019 at 11:42
  • Actually I said thankyou, and gave you criticism, you took that and decided to write something snarky back, if we're going to start with functional methods to perform rather than prototypical chained methods like we should be, then something much simpler like: jsfiddle.net/shannonhochkins/xsm9j610/21 Sep 11, 2019 at 1:08
2

For replacing with nothing, tckmn's answer is the best.

If you need to replace with specific strings corresponding to the matches, here's a variation on Voicu's and Christophe's answers that avoids duplicating what's being matched, so that you don't have to remember to add new matches in two places:

const replacements = {
  '’': "'",
  '“': '"',
  '”': '"',
  '—': '---',
  '–': '--',
};
const replacement_regex = new RegExp(Object
  .keys(replacements)
  // escape any regex literals found in the replacement keys:
  .map(e => e.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
  .join('|')
, 'g');
return text.replace(replacement_regex, e => replacements[e]);
1

What if just use a shorthand of if else statement? makes it a one-liner.

const betterWriting = string.replace(/[#_]/gi , d => d === '#' ? '' : ' ' );
1
  • Similar approach to the accepted answer - much simpler isn't it than creating a prototypical extension! Aug 9, 2022 at 0:53
0

String.prototype.replaceAll=function(obj,keydata='key'){
 const keys=keydata.split('key');
return Object.entries(obj).reduce((a,[key,val])=> a.replace(new RegExp(`${keys[0]}${key}${keys[1]}`,'g'),val),this)
}

const data='hids dv sdc sd {yathin} {ok}'
console.log(data.replaceAll({yathin:12,ok:'hi'},'{key}'))

1
  • 1
    Hi there, welcome to Stackoverflow. Maybe you could add a bit of an explanation about what your code is doing and why you are doing it this way? Also, there is bit of duplicate code (unformated) in your answer that you might want to clean up.
    – niels
    Jul 2, 2020 at 9:15
0

This works for Yiddish other character's like NEKUDES

var string = "נׂקֹוַדֹּוֶת";


var string_norm = string.replace(/[ְֱֲֳִֵֶַָֹֹּׁׂ]/g, '');
document.getElementById("demo").innerHTML = (string_norm);
0

Not sure why nobody has offered this solution yet but I find it works quite nicely:

var string = '#Please send_an_information_pack_to_the_following_address:'
var placeholders = [
    "_": " ",
    "#": ""
]

for(var placeholder in placeholders){
    while(string.indexOf(placeholder) > -1) {
        string = string.replace(placeholder, placeholders[placeholder])
    }
}

You can add as any placeholders as you like without having to update your function. Simple!

2
  • because it's overcomplicated compared to other solutions Dec 1, 2021 at 5:04
  • 1
    Doesn't use regex, doesn't use chaining, uses simple loops that everyone can understand, doesn't require updates to the function when the input changes, allows abstraction of the placeholders. Newer (and older) developers are going to immediately understand the code, doesn't require esoteric knowledge of abstract language features. I put it to you that this is the simplest and most flexible solution on offer. Dec 2, 2021 at 22:54
0

One function and one prototype function.

String.prototype.replaceAll = function (search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'gi'), replacement);
};


            var map = {
                '&': 'and ',
                '[?]': '',
                '/': '',
                '#': '',
                // '|': '#65 ',
                // '[\]': '#66 ',
                // '\\': '#67 ',
                // '^': '#68 ',
                '[?&]': ''
            };


             var map2 = [
                {'&': 'and '},
                {'[?]': ''},
                {'/': ''},
                {'#': ''},                
                {'[?&]': ''}
            ];

            name = replaceAll2(name, map2);
            name = replaceAll(name, map);


    function replaceAll2(str, map) {            
        return replaceManyStr(map, str);
    }  

    function replaceManyStr(replacements, str) {
        return replacements.reduce((accum, t) => accum.replace(new RegExp(Object.keys(t)[0], 'g'), t[Object.keys(t)[0]]), str);
    }
0

Or option working fine for me Example let sample_string = <strong>some words with html tag </strong> | . need to remove the strong tag and "|" text. the code is like this = sample_string.replace(/\|(.*)|<strong>|<\/strong>/g,"")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.