Replace multiple characters in one replace call

前端 未结 15 2297
失恋的感觉
失恋的感觉 2020-11-22 17:24

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 no

相关标签:
15条回答
  • 2020-11-22 17:27

    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.

    0 讨论(0)
  • 2020-11-22 17:28

    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.

    0 讨论(0)
  • 2020-11-22 17:28

    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}'))

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

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

    0 讨论(0)
  • 2020-11-22 17:28

    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]);
    
    0 讨论(0)
  • 2020-11-22 17:35

    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];})
    
    0 讨论(0)
  • 2020-11-22 17:38

    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

    0 讨论(0)
提交回复
热议问题