Javascript escape single quote

Javascript escape single quote in js code example

Solution 2: A few ways to do this : 1 — replacing the colons for square brackets which will create an array of string values then you just have to worry about sorting thru the array length, this will increase your processing time but if your app is not too big it should not make a big difference. 2 — Use to escape single quotes in strings or to escape double quotes. Solution 1: Like this: Inside double quotes, single quotes are normal characters and vice versa.

How to escape a single quote inside a JavaScript variable

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:

Using will encode special characters for correctly outputting into HTML, such as ‘ , » , and & (among others).

And then change your HTML to be:

" />" data-question="" />" data-question-data-type="" />" data-audio-path="" />" data-security-question-type="" />" /> 

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 >); >); 

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:

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.

Читайте также:  Online html css code editor

My suggestion is to just not do that; Instead, call a wrapper function. That way, you don’t have to worry about escaping anything.

 function editSeqQuestion(. ) < . >function wrapperFunction() 

Html — How do I escape a single quote ( ‘ ) in JavaScript?, 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. Usage exampledocument.getElementById(«something»).innerHTML = «»;Feedback

Escape single quote with JavaScript

If you would be using Java, maybe you can do the below in Java.

import org.apache.commons.lang.StringEscapeUtils; . String result = StringEscapeUtils.escapeJavaScript(jsString); 

Just prepend every single quote with a backslash. Like the following: StringEscapeUtils.escapeHtml(map[i].get(«text»).toString()).replace(«\'»,»\\'»)

But your problem is not only in the single quote. There is also the double quote («) and the backslash itself (\).

Use the same technique as shown before. You can also use regular expressions, but I showed you the simplest way.

To check the escape characters, look at the URL http://docs.oracle.com/javase/tutorial/java/data/characters.html.

Escape quotes in JavaScript, Add a comment. 2. Please find in the below code which escapes the single quotes as part of the entered string using a regular expression. It validates if the user-entered string is comma-separated and at the same time it even escapes any single quote (s) entered as part of the string.

Escape single quotes in jQuery or JavaScript

$("#spn_err").text("'" + $('#txt1').val() + "' is not valid"); 

Inside double quotes, single quotes are normal characters and vice versa. Otherwise you can escape them by prepending a backslash: «\»» or ‘\» .

$("#spn_err").text('\'' + $("#txt1").attr("value") + '\' is not valid'); 

It is close. Use the .val() method:

$('#spn_err').text($('#txt1').val() + ' is not valid'); 

Escaping single quotes in JavaScript string for, 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 …

Unable to escape single quote

The way you are building up this query is exactly what you don’t want to do. It leaves you completely open to SQL injection.

To avoid this, you need to parameterize your query. The added benefit here it will take care of all escaping.

Here is an example, straight from the MS docs, demonstrating how to perform parameterized queries with the node.js driver for SQL Server.

Your code, following this paradigm will look something like:

exports.addEntry = (req, res, nomPage, nomTable, data) => < Object.keys(data).forEach(function (k, id) < console.log(data[k]); if (data[k] != null) < if (id >0) < columnString += `,`; dataString += `,`; >columnString += `$`; dataString += `@$`; > >); try < if (!data) throw new Error("Input not valid"); if (data) < var sqlQuery = `INSERT INTO $($) VALUES ($)`; connect.connectDatabase(sqlQuery, (data, err) => < [. ] 

All that changed was the operating constructing the dataString .

Note, you'll now need to feed parameters into your command execution to replace the data you were embedding before.

A few ways to do this : 1 - replacing the colons for square brackets which will create an array of string values then you just have to worry about sorting thru the array length, this will increase your processing time but if your app is not too big it should not make a big difference.

Читайте также:  Убираем туман css v34

2 - Use \' to escape single quotes in strings or \" to escape double quotes.

Let me know if that helped as this is a quick answer.

Single quote escape in JavaScript function parameters, This will fail if the string contains ", , '\' or any other entity that encodes single or double quotes or backslash. For example, the string 'foo " onmouseover=alert (1) contains no single quote, yet when embedded in an HTML attribute, exploits an XSS vulnerability.

Источник

Javascript escape single quote

Last updated: Dec 26, 2022
Reading time · 4 min

banner

# Table of Contents

# Escape Quotes in a String in JavaScript

To escape a single or double quote in a string, use a backslash \ character before each single or double quote in the contents of the string, e.g. 'that\'s it' .

Copied!
const escapeSingle = 'it\'s a string'; console.log(escapeSingle) // 👉️ it's a string const escapeDouble = "bobby\"hadz" console.log(escapeDouble) // 👉️ bobby"hadz

When we use the backslash character to escape a single or a double quote, we instruct JavaScript that we want to treat the quote as a literal single or double quote character and not as an end-of-string character.

If you use a single quote in a string that is wrapped in single quotes, you would terminate the string prematurely.

However, this is not the case when you use a backslash to escape the single quote.

# Escaping double quotes in a String

You can use the same approach to escape a double quote in a string.

Copied!
const escapeDouble = "He said: \"test 123\"" console.log(escapeDouble) // 👉️ He said: "test 123"

We use a backslash \ character to escape each double quote in the string.

# Escaping quotes in a String with String.replaceAll()

You can also use the String.replaceAll() method to escape the quotes in a string.

Copied!
// ✅ escape every single quote const str = "it's a string"; console.log(str); // 👉️ it's a string const result = str.replaceAll("'", "\\'"); console.log(result); // 👉️ it\'s a string

The String.replaceAll() method returns a new string with all matches of a pattern replaced by the provided replacement.

The method takes the following parameters:

Name Description
pattern The pattern to look for in the string. Can be a string or a regular expression.
replacement A string used to replace the substring match by the supplied pattern.

The code sample escapes every single quote in a string.

Copied!
// ✅ escape every single quote const str = "it's a string"; console.log(str); // 👉️ it's a string const result = str.replaceAll("'", "\\'"); console.log(result); // 👉️ it\'s a string

The same approach can be used to escape double quotes in a string.

Copied!
// ✅ escape every double quote const str = 'it"s a string'; console.log(str); // 👉️ it"s a string const result = str.replaceAll('"', '\\"'); console.log(result); // 👉️ it\"s a string

The String.replaceAll() method returns a new string with the matches of the pattern replaced. The method doesn't change the original string.

Читайте также:  Introduction to programing with java

Strings are immutable in JavaScript.

# Alternating quotes to avoid using backslashes

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 123"' console.log(withDouble) // 👉️ He said: "test 123"

We alternate between double and single quotes, so we don't have to escape them.

# Using backticks instead of backslashes

Note that you can also use backticks when defining a variable that stores a string. This allows you to use both single and double quotes in the string without having to escape them.

Copied!
const withBoth = `it's a "test 123"`; console.log(withBoth) // 👉️ it's a "test 123"

The string is wrapped in backticks so we don't have to escape the single and double quotes in its contents.

To add a backslash \ character to a string, add two backslashes next to one another.

The first backslash escapes the second, so the second is taken literally.

Copied!
const addBackslash = "He said: \\\"test 123\\\"" console.log(addBackslash) // 👉️ He said: \"test 123\"

We have 3 backslashes next to one another. The first backslash escapes the second, so it is interpreted literally by JavaScript. The third backslash is used to escape the double quotes.

Here's a more realistic example, where we only add a backslash to the string.

Copied!
const addBackslash = "BMW \\1996\\" console.log(addBackslash) // 👉️ BMW \1996\

# Showing the escape characters in a string

If you need to show the escape characters in a string, use the JSON.stringify() method.

Copied!
const addBackslash = 'BMW \\1996\\'; console.log(addBackslash); // 👉️ BMW \1996\ const withEscapeChars = JSON.stringify(addBackslash); console.log(withEscapeChars); // 👉️ "BMW \\1996\\"

The JSON.stringify method converts a JavaScript value to a JSON string.

When a value is converted to a JSON string, its output contains the escape characters.

# Avoiding inline event handlers in HTML code

If you got the error when using inline event handlers in HTML code, the best solution is to rewrite your code to use JavaScript and not use an inline event handler.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> div id="box">bobbyhadz.comdiv> script type="module" src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const box = document.getElementById('box'); function handleClick() box.style.background = 'lime'; > box.addEventListener('click', handleClick); box.innerHTML = ` div id="box"> p title="example">bobbyhadz.comp> p>Hello worldp> div> `;

You can select the DOM element using the document.getElementById() method or the querySelector method.

Then you can add an event listener to the element or update its inner HTML markup.

Notice that we used backticks when setting the innerHTML property.

This enables us to use both single and double quotes when constructing the HTML markup.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью