Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

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

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 know whether it actually replaced anything apart from comparing the result with the original string?

question from:https://stackoverflow.com/questions/5257000/how-to-know-if-javascript-string-replace-did-anything

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...