javascript 如何用正则表达式搜索替换并在javascript中保持大小写为原始
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13721758/
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 search replace with regex and keep case as original in javascript
提问by Graham
Here is my problem. I have a string with mixed case in it. I want to search regardless of case and then replace the matches with some characters either side of the matches.
这是我的问题。我有一个大小写混合的字符串。我想不管大小写都进行搜索,然后用匹配项两侧的一些字符替换匹配项。
For example:
例如:
var s1 = "abC...ABc..aBC....abc...ABC";
var s2 = s.replace(/some clever regex for abc/g, "#"+original abc match+"#");
The result in s2 should end up like:
s2 中的结果应该是这样的:
"#abC#...#ABc#..#aBC#....#abc#...#ABC#"
Can this be done with regex? If so, how?
这可以用正则表达式完成吗?如果是这样,如何?
回答by DhruvPathak
This can be done using a callback function for regex replace.
这可以使用用于正则表达式替换的回调函数来完成。
var s1 = "abC...ABc..aBC....abc...ABC";
var s2 = s1.replace(/abc/ig, function (match) {
return "#" + match + "#" ;
}
);
alert(s2);
demo : http://jsfiddle.net/dxeE9/
回答by John Dvorak
This can be done using a back-reference:
这可以使用反向引用来完成:
var s2 = s.replace(/your complex regex/g, "#$&#");
The back-reference $&
brings in the entire match. If you want to match "abc" in any case:
反向引用$&
引入了整个匹配。如果你想在任何情况下匹配“abc”:
var s2 = s.replace(/abc/ig, "#$&#");
If you only want to bring in part of a larger pattern, you can refer to it by its group number:
如果你只想引入一个较大的模式的一部分,你可以通过它的组号来引用它:
var s2 = s.replace(/some (part) of a string/ig, "##");
Groups are numbered by their opening parenthesis, from left to right, from $1
to $9
.
组按其左括号编号,从左到右,从$1
到$9
。
回答by Anirudha
You can also do this
你也可以这样做
yourString.replace(/([a-z]+)/ig, "##")