0

My object string as following

var objStr = "{'light': '5', 'color': '2', 'defect': 'Hello Wo'rld'}";

replace single quote in Hello Wo'rld string like this

objStr = objStr.replace(/([\w]\'[\w])/g, "\\'");

result string is (objStr )

"{'light': '5', 'color': '2', 'defect': 'Hello W\'ld'}"   // objStr 

And then I get the object like this

eval('(' + objStr + ')');   // {light: "5", color: "2", defect: "Hello W'ld"}

where the 'o' and 'r', what problem with my regular expression?

And what if the single quote between two Chinese characters? (regular expression)

Thank you for your kindly help.

Shawn Wu
  • 487
  • 7
  • 18

2 Answers2

1

So here:

[\w]\'[\w]

You are selecting a word character, a ' and then another word character. In your string this will match

o'r

And that's what you are replacing with \'. You are replacing the whole match not part of the match.

There are a couple of approaches you can use to fix this. First is to use look behinds and look aheads. Unfortunately, javascript doesn't support look behinds. But in other flavors of Regex, you could do this:

(?<=\w)'(?=\w)

Another thing you can do is use non-capturing groups

(?:\w)'(?:\w)

This will match the word character before and after, but it won't be captured as part of the match.

The other option is just to put the part that you want to keep in the replace. So you can do:

objStr.replace(/(\w)\'(\w)/g, "$1\\'$2");

This captures your preceding and following characters and puts them back in the substitution (as $1 and $2).

The final, and probably most correct option, is to use JSON, since you seem to be trying to recreate JSON. The correct JSON string would be:

var objStr = '{"light": "5", "color": "2", "defect": "Hello Wo\'rld"}';

Which solves the whole problem and now you can use JSON.parse instead of eval

Matt Burland
  • 44,552
  • 18
  • 99
  • 171
0

Use:

objStr = objStr.replace(/([\w])\'([\w])/g, "$1\\'$2");

This will put the letters back. $1 = letter to the left of ' and $2 = letter to the right. Things inside parenthesis in regexp can be used like that.

Jonas Berlin
  • 3,344
  • 1
  • 27
  • 33