Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
194
rated 0 times [  198] [ 4]  / answers: 1 / hits: 148424  / 12 Years ago, tue, february 26, 2013, 12:00:00

I have a project, in which some JavaScript var is evaluated. Because the string needs to be escaped (single quotes only), I have written the exact same code in a test function. I have the following bit of pretty simple JavaScript code:



function testEscape() {
var strResult = ;
var strInputString = fsdsd'4565sd;

// Here, the string needs to be escaped for single quotes for the eval
// to work as is. The following does NOT work! Help!
strInputString.replace(/'/g, '');

var strTest = strResult = ' + strInputString + ';;
eval(strTest);
alert(strResult);
}


And I want to alert it, saying: fsdsd'4565sd.


More From » string

 Answers
34

The thing is that .replace() does not modify the string itself, so you should write something like:



strInputString = strInputString.replace(...


It also seems like you're not doing character escaping correctly. The following worked for me:



strInputString = strInputString.replace(/'/g, \');

[#79996] Monday, February 25, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marvinm

Total Points: 406
Total Questions: 104
Total Answers: 121

Location: Iceland
Member since Tue, Jan 25, 2022
2 Years ago
;