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

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!

查看更多
余生请多指教
3楼-- · 2019-01-02 20:18

You can just try this :

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

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

查看更多
怪性笑人.
4楼-- · 2019-01-02 20:25

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.

查看更多
梦醉为红颜
5楼-- · 2019-01-02 20:28

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;
}
查看更多
萌妹纸的霸气范
6楼-- · 2019-01-02 20:30

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

查看更多
登录 后发表回答