繁体   English   中英

用特殊字符替换子字符串

[英]Replace a substring with special characters

我有一个字符串,其中包含一些包含在一些特殊字符中的子字符串。 这是我的代码:

var p = 'The quick brown fox jumps over the lazy [dog]. If the [dog] reacted, was it really lazy?';

var regex = /[\\[dog\\]]/g;

console.log(p.replace(regex, 'ferret'));

代码给了我输出The quick brown fox jumps over the lazy ferretdogferret. If the ferretdogferret reacted, was it really lazy? The quick brown fox jumps over the lazy ferretdogferret. If the ferretdogferret reacted, was it really lazy? 但我期待The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy? The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?

只需删除整个模式周围的字符集,然后匹配\\[dog\\]

 var p = 'The quick brown fox jumps over the lazy [dog]. If the [dog] reacted, was it really lazy?'; var regex = /\\[dog\\]/g; console.log(p.replace(regex, 'ferret')); 

您可以使用标准JS并像下面那样处理它。

 let txt = 'The quick brown fox jumps over the lazy [dog]. If the [dog] reacted, was it really lazy?' let txt1 = txt.split(' ') txt1.map((word, i) => word.includes('dog') ? txt1[i]='ferret':null ) let sentence = txt1.join(' ') console.log(sentence) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM