Javascript Regex - Quotes to Parenthesis

后端 未结 2 548
孤独总比滥情好
孤独总比滥情好 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:02

    You could try something like

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

    Example

    "this will be \"replaced\"".replace(/"(.*)"/, "($1)")
    => this will be (replaced)
    
    "this \"this\" will be \"replaced\"".replace(/"(.*?)"/g, "($1)")
    => this (this) will be (replaced)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题