Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenate string with variable and escape characters

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=''>"
like image 784
Mr.freelance Avatar asked Jan 21 '26 23:01

Mr.freelance


1 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.

like image 61
tevemadar Avatar answered Jan 24 '26 20:01

tevemadar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!