以下是我的替换代码:
.replace(/java(script)/g,'$1')
所以"some javascript to replace"将"some script to replace"后成为"some script to replace" 。 我想要的是如果javascript以#开头,我不想用#script替换#script 。 所以结果
"some #javascript to replace"应该是"some #javascript to replace"
我应该使用什么样的正则表达式?
The following is my replacement code:
.replace(/java(script)/g,'$1')
So "some javascript to replace" will become "some script to replace" after replacement. What I want is if the javascript starts with #, I don't want to replace #javascript with #script. So the result of
"some #javascript to replace" should be "some #javascript to replace"
What regex should I use?
最满意答案
使用以下正则表达式替换:
var s = "some javascript #javascript to replace"; s = s.replace(/(^|[^#])java(script)/g,'$1$2'); console.log(s);细节 :
(^|[^#]) - 捕获组1匹配字符串的开头或除#以外的任何字符# java - 一个文字char序列java (script) - 捕获与文字字符序列script匹配的组2。在替换模式中,捕获的部分将重新插入到生成的字符串中,只有在没有#前面并且后跟script才会有效地删除java 。
Use the following regex replacement:
var s = "some javascript #javascript to replace"; s = s.replace(/(^|[^#])java(script)/g,'$1$2'); console.log(s);Details:
(^|[^#]) - capturing group 1 matching either the start of string or any char other than # java - a literal char sequence java (script) - capturing group 2 matching a literal char sequence script.In the replacement pattern, the captured parts are re-inserted into the resulting string, effectively removing java only if not preceded with # and followed with script.
更多推荐
发布评论