如何知道 JavaScript string.replace() 是否做了什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5257000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to know if JavaScript string.replace() did anything?
提问by Alex Kapranoff
The replacefunction 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?
该replace函数返回带有替换的新字符串,但如果没有任何要替换的单词,则返回原始字符串。除了将结果与原始字符串进行比较之外,有没有办法知道它是否真的替换了任何东西?
采纳答案by Kobi
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 replacecallback to achieve that in a single pass:
如果您也不希望那样,您可以滥用replace回调以通过一次传递来实现:
var replaced = false;
var newStr = str.replace(/i/g, function(token){replaced = true; return '!';});
回答by Alnitak
Comparing the before and after strings is the easiest way to check if it did anything, there's no intrinsic support in String.replace().
比较前后字符串是检查它是否做了任何事情的最简单方法,在String.replace().
[contrived example of how '==' might fail deleted because it was wrong]
[人为示例说明“==”可能会因为错误而无法删除]
回答by Stanislav Yaglo
As a workaround you can implement your own callback function that will set a flag and do the replacement. The replacementargument of replacecan accept functions.
作为一种解决方法,您可以实现自己的回调函数,该函数将设置一个标志并进行替换。的replacement参数replace可以接受函数。
回答by puchu
Javascript replaceis defected by design. Why? It has no compatibility with string replacement in callback.
Javascriptreplace在设计上有缺陷。为什么?它与回调中的字符串替换不兼容。
For example:
例如:
"ab".replace(/(a)(b)/, "")
> "ab"
We want to verify that replace is done in single pass. I was imagine something like:
我们想验证替换是在单程中完成的。我在想象这样的事情:
"ab".replace(/(a)(b)/, "", function replacing() { console.log('ok'); })
> "ab"
Real variant:
真实变体:
"ab".replace(/(a)(b)/, function replacing() {
console.log('ok');
return "";
})
> ok
> ""
But function replacingis designed to receive $0, $1, $2, offset, stringand we have to fight with replacement "$1$2". The solution is:
但是函数replacing被设计为接收$0, $1, $2, offset, string,我们不得不与替换“$1$2”作斗争。解决办法是:
"ab".replace(/(a)(b)/, function replacing() {
console.log('ok');
// arguments are "a".replace(/(a)/, "")
> "a"
"a".replace(/(a)/, "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);
1")
> "const regex = /foo/;
const yourString = 'foo bar';
if (regex.test(yourString)) {
console.log('yourString contains regex');
}
1"
, , ..., offset, string
return Array.from(arguments).slice(1, -2)
.reduce(function (pattern, match, index) {
// '' from strings like ' ' shouldn't be replaced.
return pattern.replace(
new RegExp("\$" + (index + 1) + "(?=[^\d]|$)", "g"),
match
);
}, "");
});
> ok
> "ab"
This solution is not perfect. String replacement itself has its own WATs. For example:
这个解决方案并不完美。字符串替换本身有它自己的 WAT。例如:
##代码##If you want to care about compatibility you have to read specand implement all its craziness.
如果您想关心兼容性,则必须阅读规范并实现其所有疯狂之处。
回答by xanatos
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.
你可以搜索一下。如果搜索成功,则从找到的索引开始替换子字符串,然后重新组合字符串。这可能会更慢,因为您正在生成 3 个字符串而不是 2 个。
##代码##回答by Bill Keller
回答by bw_üezi
have a look at string.match() or string.search()
看看 string.match() 或 string.search()
回答by gnur
With indexOfyou can check wether a string contains another string.
Seems like you might want to use that.
随着indexOf您可以请检查是否一个字符串包含另一个字符串。
似乎您可能想使用它。

