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, "\\'");
Answer from Nikita Tkachenko on Stack Overflow
Top answer
1 of 5
204

You should always consider what the browser will see by the end. In this case, it will see this:

<img src='something' onmouseover='change(' ex1')' />

In other words, the "onmouseover" attribute is just change(, and there's another "attribute" called ex1')' with no value.

The truth is, HTML does not use \ for an escape character. But it does recognise &quot; and &apos; as escaped quote and apostrophe, respectively.

Armed with this knowledge, use this:

document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(&quot;ex1&quot;)' />";

... That being said, you could just use JavaScript quotes:

document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\"ex1\")' />";
2 of 5
187

The answer here is very simple:

You're already containing it in double quotes, so there's no need to escape it with \.

If you want to escape single quotes in a single quote string:

var string = 'this isn\'t a double quoted string';
var string = "this isn\"t a single quoted string";
//           ^         ^ same types, hence we need to escape it with a backslash

or if you want to escape \', you can escape the bashslash to \\ and the quote to \' like so:

var string = 'this isn\\\'t a double quoted string';
//                    vvvv
//                     \ ' (the escaped characters)

However, if you contain the string with a different quote type, you don't need to escape:

var string = 'this isn"t a double quoted string';
var string = "this isn't a single quoted string";
//           ^        ^ different types, hence we don't need escaping
Discussions

I need help with escaping literal quotes
Tell us what’s happening: hey Your code so far var myStr = "I am a/'Double quoted\"string inside\"double quotes\"."; Your browser information: User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36. More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
June 19, 2019
Escaping both single and double quotes
Use the backticks and don't unnecessarily quote object keys. More on reddit.com
🌐 r/learnjavascript
4
2
December 26, 2022
Single quote escape in JavaScript function parameters - Stack Overflow
Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... onclick="Javascript:INSERT_PRODUCT('188267','WILL AND GRACE','32311','L'ANNIVERSARIO DINOZZE ','20101113|04|18|','13/11/2010 0.00.00','CANALE 5 ',this);" But I need to escape them inside a function call since I do not know the values that will be passed (db variables ... More on stackoverflow.com
🌐 stackoverflow.com
html - How to escape all single and double quotes in JavaScript - Stack Overflow
This is not really what the OP ... on the variable str, there's no fear about modifying original string ;-) 2016-09-27T08:52:56.25Z+00:00 ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... I’m Jody, the Chief Product and Technology Officer at Stack Overflow. Let’s... Release notes and bug fixes for beta.stackoverflow.com · 223 How do I escape a single quote ( ' ) in JavaScript... More on stackoverflow.com
🌐 stackoverflow.com
🌐
SitePoint
sitepoint.com › javascript
Escaping Single and Double Quotes in a generated String - JavaScript - SitePoint Forums | Web Development & Design Community
April 23, 2006 - Hi, I’ve been wrestling with this issue for a while and I’m hoping someone can help. I am building an administrative panel for one of my applications using ajax so I’m using lots of javascript to display information on…
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
I need help with escaping literal quotes - JavaScript - The freeCodeCamp Forum
June 19, 2019 - Tell us what’s happening: hey Your code so far var myStr = "I am a/'Double quoted\"string inside\"double quotes\"."; Your browser information: User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/…
🌐
EyeHunts
tutorial.eyehunts.com › home › javascript escape a single quote in a string variable | example code
JavaScript escape a single quote in a string variable | Example code
June 24, 2021 - Using Regex and replace method will escape single quote in string variable in JavaScript. Let's see simple HTML example cdoe
🌐
Linux Hint
linuxhint.com › escape-a-single-quote-from-a-string-in-javascript
How to Escape a Single Quote From a String in JavaScript
June 3, 2023 - Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
javascript.com
javascript.com › learn › strings
JavaScript Strings: The Basic Methods and Functions | JavaScript.com
That means strings containing single ... to use single quotes. Alternatively, you can use a backslash \ to escape the quotation marks. This lets JavaScript know in advance that you want to use a special character.
Find elsewhere
🌐
W3Schools
w3schools.com › js › js_strings.asp
JavaScript Strings
1 month ago - A JavaScript string is zero or more characters written inside quotes. ... let carName1 = "Volvo XC60"; // Double quotes let carName2 = 'Volvo XC60'; // Single quotes Try it Yourself »
🌐
Flexiple
flexiple.com › javascript › double-vs-single-quotes-javascript
'Single' vs "Double" quotes for strings in javascript - Flexiple
March 10, 2022 - Wise selection of quoting can help you from escaping single (') or double(") quotes within a string. For example, if you wish to store a HTML snippet in a variable, you can use double quotes (") for HTML attribute values and use single quotes (') for enclosing the JavaScript string:
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-escape-all-single-and-double-quotes-in-javascript
How to Escape All Single and Double Quotes in JavaScript? - GeeksforGeeks
November 8, 2024 - To escape all single and double quotes in a string using JavaScript, you can use a regular expression with the replace method.
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-escape-quotes-in-string
How to Escape Quotes in a String using JavaScript | bobbyhadz
March 2, 2024 - Strings are immutable in JavaScript. Escaping a quote can be avoided by changing the outer quotes of the string. ... Copied!const withSingle = "it's a string"; console.log(withSingle) // 👉️ it's a string const withDouble = 'He said: "test ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-work-with-strings-in-javascript
How To Work with Strings in JavaScript | DigitalOcean
August 24, 2021 - However, when we are working to use consistent syntax within project programming files, this can be difficult to maintain throughout a codebase. We can use the backslash (\) escape character to prevent JavaScript from interpreting a quote as the end of the string.
🌐
EyeHunts
tutorial.eyehunts.com › home › javascript escape single quote function parameter | example code
JavaScript escape single quote function parameter | Example code
June 24, 2021 - Use ‘escape sequence’. Place a backslash \ before a single quote to escape a single quote function parameter in JavaScript.
🌐
Reddit
reddit.com › r/learnjavascript › escaping both single and double quotes
r/learnjavascript on Reddit: Escaping both single and double quotes
December 26, 2022 -

Hey,

I'm creating an object which contains user-typed content and the very same object will be printed / embeded somewhere else after. The tricky thing is :

- The object uses "xxx" for strings

- The place where it will be embeded as a text uses '{"mykey" : "myobject"}'

The object's creation is done using js ; the embed is in a bash environment. These are two separate scripts. So, basically, I want to escape all quotes and single quotes but also avoid escaping a user-typed quote like in this case \', which would output \\' and unescape the quote by escaping the escape itself. When I build my string, it seems that the quotes are successfully replaced with escaped ones. But then when I return the string, is seems that the escape is taken in account so the escapes disappears. What I'm trying to explain is that apparently when I return the escaped string, JS uses it to return the unescaped version.

How can I escape quotes and keep the string escaped for later use ? thanks

Top answer
1 of 4
2

The correct way to handle this is to escape the HTML in your JSP file, and also bind the event unobtrusively. The values from the database can be put in data-* attributes. For example, your HTML would be something like the following. Include this at the top of your JSP:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Using <c:out /> will encode special characters for correctly outputting into HTML, such as ', ", and & (among others).

And then change your HTML to be:

<input type="button" id="btnSubmit" value="Edit"
       data-question-id="<c:out value="${QuestionId}" />"
       data-question="<c:out value="${Question}" />"
       data-question-data-type="<c:out value="${QuestionDataType}" />"
       data-audio-path="<c:out value="${AudioPath}" />"
       data-security-question-type="<c:out value="${securityQuestionType}" />" />

And your JavaScript:

window.onload = function () {
    document.getElementById("btnSubmit").onclick = function () {
        var questionId = this.getAttribute("data-question-id"),
            question = this.getAttribute("data-question"),
            questionDataType = this.getAttribute("data-question-type"),
            audioPath = this.getAttribute("data-audio-path"),
            securityQuestionType = this.getAttribute("data-security-question-type");
        editSeqQuestion(questionId, question, questionDataType, audioPath, securityQuestionType);
    };
};

Of course, it is "better" to use addEventListener, instead of setting onload and onclick. So you might use this:

function addEvent(element, eventName, callback) {
    if (element.addEventListener) {
        element.addEventListener(eventName, callback, false);
    } else if (element.attachEvent) {
        element.attachEvent("on" + eventName, callback);
    }
}

and then bind events like:

addEvent(window, "load", function () {
    addEvent(document.getElementById("btnSubmit"), "click", function () {
        // The code from above
    });
});

Reference:

  • addEventListener: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener
2 of 4
0

Yes, you have a few options. Two are the most obvious:

  1. Tackle it server side and have your value come into your page from your JSP already string replaced with an html entity ' being the most logical (then you don't worry about your quote notation.
  2. Abstract it one way or the other into a js variable. Passing a js variable into a function obviates the need to escape the quotes (at least while passing it).

The first option is the least amount of work in some ways. Depending on how dynamic this is supposed to be, you might opt for the second option. In that case, I would suggest the jsp building a nice object or array for you in js which you can then reference (I am guessing you have more than one question set). Have the jsp set a unique id on each element and then have the onclick reference the array by the same id notation to use the object/array stored values as necessary. Go one step farther and bind your function to the elements and follow unobtrusive code methods.

In the short run, your page might end up looking something like this:

<script>
  aQs = [
   {v: 72, q: 'What is child&apos;s name', t: 'AN', s: 'nick.wav', title: 'Sec'},
   {v: 23, q: 'What city', t: 'AN', s: 'city.wav', title: 'Sec'}
  ];

  function edQ(qId) {
    dosomething(aQs[qId]);
  }
</script>

<input type="button" id="btn_0" Value="Edit" onclick="edQ(this.id.split('_')[1])" />
<input type="button" id="btn_1" Value="Edit" onclick="edQ(this.id.split('_')[1])" />

In either case, I think the easiest/safest thing to do to generally handle the ' is to replace it server side with an html entity.

🌐
Java2Blog
java2blog.com › home › javascript › escape apostrophe in javascript
Escape Apostrophe in JavaScript - Java2Blog
May 23, 2022 - You can use escape character backslash(\) to escape quotes in Javascript. It will prevent javascript to interpret end of String. You can use \' to escape single quotes.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-use-escape-characters-to-correctly-log-quotes-in-a-string-using-javascript
How to use Escape Characters to Log Quotes in JavaScript? | GeeksforGeeks
September 9, 2024 - By placing a backslash (`\`) before a quote, you can ensure that the quote is treated as part of the string rather than as a delimiter. This is essential for correctly logging strings that contain both single and double quotes.