text = abc "def" g'i' jklm'no' p"qrs uv w"
应该成为abc !string! g !string! jklm!string! p !string!
到目前为止:
if(/(?:'[^']+'|"[^"]+")/.test(text){
text = text.replace(/(?:'[^']+'|"[^"]+")/, "!string!");
}
(杰瑞的回答)
它只替换用''或'“括起来的第一个文本。这实际上与我之前的问题有关,但我认为这更复杂:How to search for the second occurence of ' or " in regex?
答案 0 :(得分:2)
g修饰符执行全局匹配
text = text.replace(/(?:'[^']+'|"[^"]+")/g, "!string!");
答案 1 :(得分:2)
试试这个
str = "abc \"def\" g'i' jklm'no' p\"qrs uv w\"";
mystring = str.replace(/("|')+[a-z ]+("|')/g, '!sring!');
alert(mystring);
<强>输出强>:
abc !string! g !string! jklm!string! p !string!
答案 2 :(得分:0)
使用全局参数“g”
str.replace(/blue/g,"red");
答案 3 :(得分:0)
这个怎么样
var str = "abc \"def\" g'i' jklm'no' p\"qrs uv w\"";
var regexp = /("|')[a-z ]+("|')/g;
console.log(str.replace(regexp,'!string!'));
结果:abc !string! g!string! jklm!string! p!string!