[英]How to replace a string which is not in quotes
我在以下情况中挣扎,我有一个多行字符串,其中多次包含单词test,该字符串是:
Hello my name is "test" im a test
test is testing
我需要替换所有未用引号引起来的test -string,每个发现的字符串应后接至少1个空格或换行符,否则上述字符串将转换为:
Hello my name is "test" im a HELLOWORLD
HELLOWORLD is testing
test -string也可以由空格前缀,但也不能没有空格。
我已经发现的是一种只替换不在引号内的字符串的方法:
str.replace(/(test)(?=(?:[^"]|"[^"]*")*$)/, 'HELLOWORLD')
能有人帮我找到其他规则吗?
您可以使用:
var str = 'Hello my \'test\' name is "test" im a test\ntest is testing';
var repl = str.replace(/("[^"]*"|'[^']*')|\btest\b/g, function($0, $1) {
return ($1 == undefined) ? "HELLOWORLD" : $1; });
输出:
Hello my 'test' name is "test" im a HELLOWORLD
HELLOWORLD is testing
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.