javascript - How do I Specify single quote in object value by regular expression -


my object string following

var objstr = "{'light': '5', 'color': '2', 'defect': 'hello wo'rld'}"; 

replace single quote in hello wo'rld string this

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

result string (objstr )

"{'light': '5', 'color': '2', 'defect': 'hello w\'ld'}"   // objstr  

and object this

eval('(' + objstr + ')');   // {light: "5", color: "2", defect: "hello w'ld"} 

where 'o' , 'r', what problem regular expression?

and if single quote between 2 chinese characters? (regular expression)

thank kindly help.

so here:

[\w]\'[\w] 

you selecting word character, ' , word character. in string match

o'r

and that's replacing \'. replacing whole match not part of match.

there couple of approaches can use fix this. first use behinds , aheads. unfortunately, javascript doesn't support behinds. in other flavors of regex, this:

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

another thing can use non-capturing groups

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

this match word character before , after, won't captured part of match.

the other option put part want keep in replace. can do:

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

this captures preceding , following characters , puts them in substitution (as $1 , $2).

the final, , correct option, use json, since seem trying recreate json. correct json string be:

var objstr = '{"light": "5", "color": "2", "defect": "hello wo\'rld"}'; 

which solves whole problem , can use json.parse instead of eval


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -