53

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.

2
  • A relatively safer approach may be var strResult=eval("("+strInputString+")");. Also, STRING is immutable, so string.replace() returns the replaced result, not modify the string. Commented Feb 26, 2013 at 11:15
  • 1
    Is this what you expecting jsfiddle.net/ebTtp Commented Feb 26, 2013 at 11:34

10 Answers 10

120

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, "\\'");
Sign up to request clarification or add additional context in comments.

5 Comments

For the remaining ActionScript mohicans out there, this works: var greet:String = "l'advancement"; greet = greet.split("'").join("\\'"); ExternalInterface.call("function(){console.log('" + greet + "')}");
Note that if there is a backslash in the original text, this may not work.
As already mentioned, this doesn't work in all scenarios. Look at kev's answer below, it will work everytime.
This doesn't escape backslashes, which would allow \' to go unescaped and terminate the string early. I recommend switching the wrapper to double quotes and using the JSON.stringify() answer below.
Here is a modified version that will only escape single quotes that are not already escaped.
17

Best to use JSON.stringify() to cover all your bases, like backslashes and other special characters. Here's your original function with that in place instead of modifying strInputString:

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

    var strTest = "strResult = " + JSON.stringify(strInputString) + ";";
    eval(strTest);
    alert(strResult);
}

(This way your strInputString could be something like \\\'\"'"''\\abc'\ and it will still work fine.)

Note that it adds its own surrounding double-quotes, so you don't need to include single quotes anymore.

5 Comments

@RobertMoskal Care to provide details? (I'm assuming you defined strInputString somewhere before running the above snippet, per OP's context...)
I missed the eval. That does seem extreme!
@RobertMoskal Fair enough...if you were the one who downvoted me, would you mind undoing it? :)
I can't unless you edit it. You might point out that your answer requires an eval.
@RobertMoskal OK, done. Thanks! (Note though that the eval was/is part of the OP, not my idea. I copied the OP's function here, cut a line, and changed the var strTest line for clarity.)
2

Only this worked for me:

searchKeyword.replace(/'/g, "\\\'");//searchKeyword contains "d'av"

So, the result variable will contain "d\'av".

I don't know why with the RegEx didn't work, maybe because of the JS framework that I'm using (Backbone.js)

Comments

1

I agree that this var formattedString = string.replace(/'/g, "\\'"); works very well, but since I used this part of code in PHP with the framework Prado (you can register the js script in a PHP class) I needed this sample working inside double quotes.

The solution that worked for me is that you need to put three \ and escape the double quotes. "var string = \"l'avancement\"; var formattedString = string.replace(/'/g, \"\\\'\");"

I answer that question since I had trouble finding that three \ was the work around.

Comments

1

That worked for me.

string address=senderAddress.Replace("'", "\\'");

Comments

0

There are two ways to escaping the single quote in JavaScript.

1- Use double-quote or backticks to enclose the string.

Example: "fsdsd'4565sd" or `fsdsd'4565sd`.

2- Use backslash before any special character, In our case is the single quote

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

Note: use a double backslash.

Both methods work for me.

1 Comment

Welcome to SO! Please do not provide late answers to questions that have been answered many times before that, unless you have something new to add, that other answers fail at. Also add code boxes to your code ^^
0

var str ="fsdsd'4565sd"; str.replace(/'/g,"'")

This worked for me. Kindly try this

enter image description here

Comments

0

The regular expression in the following code also handles the possibility of escaped single quotes in the string - it will only prepend backslashes to single quotes that are not already escaped:

strInputString = strInputString.replace(/(?<!\\)'/g, "\\'");

Demo: https://regex101.com/r/L1lF7J/1


Compatibility

The regex above uses negative lookbehind, which is widely supported but if using an older Javascript version, this clunkier regex (which uses a capturing group backreference instead) will also do the job:

strInputString = strInputString.replace(/(^|[^\\])'/g, "$1\\'");

Demo: https://regex101.com/r/9niyYw/1

Comments

0

For anyone who is here for something other than eval use, a single backslash may be what you're looking for - which is apparently hard to achieve with the native js replace:

"asdf'asdf'".replace(/'/g, `\\'`); 
=>
"asdf\\'asdf\\'"

We were able to use lodash to get the desired result

_.replace("asdf'asdf'", /'/g, `\\'`); 
=> 
"asdf\'asdf\'"

Comments

-2
strInputString = strInputString.replace(/'/g, "''");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.