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

前端 未结 8 1856
盖世英雄少女心
盖世英雄少女心 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:23

    If your replace has a different length from the searched text, you can check the length of the string before and after. I know, this is a partial response, valid only on a subset of the problem.

    OR

    You can do a search. If the search is successfull you do a replace on the substring starting with the found index and then recompose the string. This could be slower because you are generating 3 strings instead of 2.

    var test = "Hellllo";
    var index = test.search(/ll/);
    
    if (index >= 0) {
        test = test.substr(0, index - 1) + test.substr(index).replace(/ll/g, "tt");
    }
    
    alert(test);
    

提交回复
热议问题