Replace multiple characters in one replace call

2019-01-02 19:37发布

Very simple little question, but I don't quite understand how to do it.

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 chaining commands like this, but is there another way to do it in one?

11条回答
时光乱了年华
2楼-- · 2019-01-02 20:08

Use the OR operator (|):

var str = '#this #is__ __#a test###__';
str.replace(/#|_/g,''); // result: "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. However, you could add a prototype:

String.prototype.allReplace = function(obj) {
    var retStr = this;
    for (var x in obj) {
        retStr = retStr.replace(new RegExp(x, 'g'), obj[x]);
    }
    return retStr;
};

console.log('aabbaabbcc'.allReplace({'a': 'h', 'b': 'o'}));
// console.log 'hhoohhoocc';

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

查看更多
笑指拈花
3楼-- · 2019-01-02 20:08

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];})
查看更多
孤独寂梦人
4楼-- · 2019-01-02 20:08

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 which 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:

var chars = {'a':'x','b':'y','c':'z'};
var s = '234abc567bbbbac';
s = s.replace(/[abc]/g, m => chars[m]);
console.log(s);

Output: 234xyz567yyyyxz

查看更多
美炸的是我
5楼-- · 2019-01-02 20:11

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.

查看更多
骚的不知所云
6楼-- · 2019-01-02 20:11

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')
查看更多
君临天下
7楼-- · 2019-01-02 20:14

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

查看更多
登录 后发表回答