1

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.

For example "apple" to (apple)

Any ideas?

mtear
  • 38
  • 4
  • Hi and welcome to SO. Please visit the [help] to see how to ask questions that are not closed or voted down. Hint: Add input and expected output examples plus whatever code you have so far – mplungjan Apr 19 '15 at 05:26
  • This could give you an ides http://stackoverflow.com/q/1144783/3150943 – nu11p01n73R Apr 19 '15 at 05:27
  • I'm sorry I thought the * in the context of regex would be clear. I will edit the question. – mtear Apr 19 '15 at 05:33
  • Are you certain that your quoted strings won't contain escaped quotes? (`\"`) – Touffy Apr 19 '15 at 07:09

2 Answers2

3

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.

  • This works for me thank you so much! Edit: I would accept this as the correct answer but the answer by @nu11p01n73R is more condensed. Thank you very much though. – mtear Apr 19 '15 at 05:35
  • 1
    However the regex here was correct from the start and explains why – mplungjan Apr 19 '15 at 05:40
1

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)
nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52