Javascript Regex - Quotes to Parenthesis

后端 未结 2 580
孤独总比滥情好
孤独总比滥情好 2021-01-27 02:47

I\'d like to somehow replace the string sequence \"*\" with (*) using a regex in Javascript. Replacing things between quotes to be between opening and closing parenthesis.

2条回答
  •  自闭症患者
    2021-01-27 03:22

    Try something like:

    str.replace(/"(.*?)"/g, function(_, match) { return "(" + match + ")"; })
    

    Or more simply

    str.replace(/"(.*?)"/g, "($1)")
    

    Note the "non-greedy" specifier ?. Without this, the regexp will eat up everything including double quotes up until the last one in the input. See documentation here. The $1 in the second fragment is a back-reference referring the first parenthesized group. See documentation here.

提交回复
热议问题