我想以某种方式使用Javascript中的正则表达式将字符串序列“*”替换为(*)。将引号之间的内容替换为左括号和右括号之间的内容。
例如“apple”to(apple)
有什么想法吗?
答案 0 :(得分:2)
尝试类似:
str.replace(/"(.*?)"/g, function(_, match) { return "(" + match + ")"; })
或更简单
str.replace(/"(.*?)"/g, "($1)")
请注意“非贪婪”说明符?
。如果没有这个,正则表达式会占用所有内容,包括双引号直到输入中的最后一个。请参阅文档here。第二个片段中的$1
是引用第一个带括号的组的反向引用。请参阅文档here。
答案 1 :(得分:1)
您可以尝试类似
的内容replace(/"(.*?)"/g, "($1)")
示例强>
"this will be \"replaced\"".replace(/"(.*)"/, "($1)")
=> this will be (replaced)
"this \"this\" will be \"replaced\"".replace(/"(.*?)"/g, "($1)")
=> this (this) will be (replaced)