concatenate string with variable and escape characters

Viewed 2289

I have this js :

var title = "firts title isn't working";
var html = "<input type='text' value='${title}'>";

I want to get this as result:

// "<input type='text' value='firts title isn't working'>"

but I get this !!!

// "<input type='text' value='firts title isn' t='' working=''>"
4 Answers

If you do not need a mix of single and double quotes, you can use doubles in the template and then the single in the text will work:

var title = "firts title isn't working";
var html = `<input type="text" value="${title}">`;
document.body.innerHTML=html;

Otherwise HTML is HTML, and as @Barmar pointed out it has no escape characters...
... but, it has entities, and then you have both, regardless of the surrounding ones:

var title = "&quot;firts&quot; title isn&apos;t working";
var html = `<input type='text' value='${title}'>`;
document.body.innerHTML=html;

(What is firts?)

And of course, you can do the replacement in code, so you can have "readable" strings, and .replace("\'","&apos;"); them later.

thanks guys I solved it like this:

var title = "some data \" && \' "; // get it from user input

var chars_toEscape = {'\'':'&apos;', '\"':'&quot;', "\`":"&#96;"};
title = title.replace(/['"`]/g, char => chars_toEscape[char]);

var html = `<input type="text" value="${title}">`;

// as result input contain as value: some data " && ' 

Use const.

Using escaped string:

const title = "first title isn\\'t working";
const html = "<input type='text' value='${title}'>";

Use ES6 template string:

const title = `first title isn't working`;
const html = "<input type='text' value='${title}'>";

Not sure whether the second one will work for you. Depends on the templating function you are using.

You didn't show in your question how the two get combined, and that will influence what will work and what won't.

try this:

var title = "firts title isn't working";
var html = "<input type='text' value='"+title+"'>";
alert(html);

Related