目前我在 javascript 中有一个基本的正则表达式,用于用分号替换字符串中的所有空格。字符串中的某些字符包含引号。理想情况下,我想用分号替换空格,但引号内的空格除外。
var stringin = "\"james johnson\" joe \"wendy johnson\" tony";
var stringout = stringin.replace(/\s+/g, ":");
alert(stringout);
谢谢 罗宾
最佳答案
尝试这样的事情:
var stringin = "\"james johnson\" joe \"wendy johnson\" tony";
var stringout = stringin.replace(/\s+(?=([^"]*"[^"]*")*[^"]*$)/g, ":");
请注意,当您的字符串中存在转义引号时,它会中断:
"ab \" cd" ef "gh ij"
关于正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1680217/