Javascript 用于替换不在引号之间的空格的正则表达式
我想删除给定字符串中的所有空格,如下所示Javascript 用于替换不在引号之间的空格的正则表达式,javascript,regex,Javascript,Regex,我想删除给定字符串中的所有空格,如下所示 const mystring = ` This is an example string with 'single quotes' and "big quotes"! No that "this \" special \" " notation with escaped quotes should also not be matched `; const result = `Thi
const mystring = `
This is an example string with 'single quotes' and "big quotes"!
No that "this \" special \" " notation with escaped quotes should also not be matched
`;
const result = `Thisisanexamplestringwith'single quotes'and"big quotes"!Nothat"this \" special \" "notationwithescapedquotesshouldalsonotbematched`;
不在引号(“
或”
)之间的,以获得类似的内容
const mystring = `
This is an example string with 'single quotes' and "big quotes"!
No that "this \" special \" " notation with escaped quotes should also not be matched
`;
const result = `Thisisanexamplestringwith'single quotes'and"big quotes"!Nothat"this \" special \" "notationwithescapedquotesshouldalsonotbematched`;
一些更好的例子更容易理解:
这是一个带有“引号和空格”的示例!
这是一个带有“引号和空格”的示例!
>第二个“引号和空格”示例
第二个“引号和空格”示例
测试“a\”b c\”d e”
测试“b c\”d e”
如果您能帮助我们继续下去,我们将不胜感激。提前谢谢
到目前为止我所做的事情: 我很确定使用Regex的Lookahead/Lookahead matcher可以完成这项工作,但我想我并没有真正使用它,因为我应该
- \s(?((?:\.[^“\])”*)
mystring.replace(/(“[^”\]*(?:\.[^”\]*)*“[^”\]*(?:\.[^'\]*))\s+/g,(x,y)=>y | | |
。但是,您以错误的方式声明了字符串,请使用const mystring=string.raw`……`;
事实上,甚至应该增强上面的正则表达式,以避免以转义引号开头的匹配。您不能在此处仅使用lookarounds,因为左侧和右侧分隔符是相同的单个字符。您好,请确保:您是否意识到您的mystring
和result
不包含文本反斜杠?我认为您实际上是想让它们出现在那里,因此您需要使用string.raw
定义字符串文本。