views:

379

answers:

2

Say i have a string that i need to evaluate in javascript such as :

window.some_class.update( 'Runner', 'update_runner', '{"runner":{"id":"1","name":"Nin's Lad" } }');

In order for eval() to evaluate it, i need to escape the apostrophe in runner_name (Nin's Lad). Is this possable with regex? I dont want to escape the single quotes around Runner and update_runner. I'd just like to escape any single quotes inside double quotes.

Thanks,

+2  A: 

This works for your specific case, but I'm sure there are some corner cases someone will point out:

yourString = yourString.replace(/"([^"]*)'([^"]*)"/g, "$1\\'$2");

Also, I'd like to point you to the last paragraph of this page:

eval is Evil

The eval function is the most misused feature of JavaScript. Avoid it.

If you're using eval, there's probably a better way to accomplish your goal.

Matt
+1 for eval being evil. ;)
Amber
I'm using rails + juggernaut plugin, unfortunately it's all geared up for evaluating update messages into method calls. Thanks for the answer and tip though!
George Sheppard
For anyone else reading this, i had to modify it slighty to add the double quotes back in. "\"$1\\'$2\""
George Sheppard
The person who wrote that, also wrote this: http://www.json.org/json2.js which contains "eval". If there is a better way to accomplish the goal, why didn't he himself use it?
Kinopiko
@Kinopiko I said there's *probably* a better way. Just because Crockford labels it as evil and misused doesn't mean there aren't very specific use cases.
Matt
@George also don't forget to add the `/g` flag at the end, so it replaces all occurrences. I edited my post to include this.
Matt
A: 
s = s.replace(/'(?=[^"]*"(?:[^"]*"[^"]*")*[^"]*$)/g, "\\'");

That matches an apostrophe if there's an odd number of quotation marks ahead of it in the string. If the string is as simple as what you posted, that should mean the apostrophe is inside a double-quoted string, but it's far from bulletproof.

Alan Moore