How to know if JavaScript string.replace() did anything?

前端 未结 8 1857
盖世英雄少女心
盖世英雄少女心 2021-02-06 21:37

The replace function returns the new string with the replaces, but if there weren\'t any words to replace, then the original string is returned. Is there a way to k

8条回答
  •  暖寄归人
    2021-02-06 22:12

    A simple option is to check for matches before you replace:

    var regex = /i/g;
    var newStr = str;
    
    var replaced = str.search(regex) >= 0;
    if(replaced){
        newStr = newStr.replace(regex, '!');
    }
    

    If you don't want that either, you can abuse the replace callback to achieve that in a single pass:

    var replaced = false;
    var newStr = str.replace(/i/g, function(token){replaced = true; return '!';});
    

提交回复
热议问题