3

I want to turn a string str = "hello, my name is \"michael\", what's your's?" into "hello, my name is <span class="name">michael</span>

How can I do that in javascript? I know how to do str replace, but how do I get the content that I selected/replaced with it.

Thanks!!!

mazlix
  • 6,003
  • 6
  • 33
  • 45

2 Answers2

8
str = "hello, my name is \"michael\", my friend's is \"bob\". what's yours?";
str.replace(/"([^"]+)"/g, '<span class="name">$1</span>');

Outputs:

hello, my name is <span class="name">michael</span>, my friend's is <span class="name">bob</span>. what's your's?
davin
  • 44,863
  • 9
  • 78
  • 78
  • oh, i've always wondered what the $1 means... I guess it gets selected text by a regex? – mazlix Jul 13 '11 at 23:16
  • @mazlix yes, the $1 gets the contents of the first capturing group. i.e. things enclosed in `()`. In this case: `[^"]+` == 1 or more non-`"` enclosed in `""` – Jacob Eggers Jul 13 '11 at 23:20
0

While @davin's answer is correct, I assume you'll want to deal instances of double quotes.

var str = "hello, my name is \"michael\", what's your's? Is is \"James\" or is it blank:\"\"";

A * in place of the + will suffice:

/"([^"]*)"/g

Although you could discard it altogether with a simple first-parse search and replace:

str.replace(/""/,"")
James Wiseman
  • 29,946
  • 17
  • 95
  • 158