如果之前的文本等于,则不替换(Not replace if the text before is equal to)

系统教程 行业动态 更新时间:2024-06-14 17:03:54
如果之前的文本等于,则不替换(Not replace if the text before is equal to)

以下是我的替换代码:

.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.

更多推荐

本文发布于:2023-04-24 14:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/0f73875aa17b63cac29cc27a04e0fe9d.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本   replace   equal   text

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!