如何知道 JavaScript string.replace() 是否做了什么? [英] How to know if JavaScript string.replace() did anything?

查看:50
本文介绍了如何知道 JavaScript string.replace() 是否做了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

replace 函数返回带有替换的新字符串,但如果没有要替换的单词,则返回原始字符串.除了将结果与原始字符串进行比较之外,有没有办法知道它是否真的替换了任何东西?

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?

推荐答案

一个简单的选择是在替换之前检查匹配:

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

如果你也不想这样,你可以滥用 replace 回调来一次性实现:

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

这篇关于如何知道 JavaScript string.replace() 是否做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆