简体   繁体   中英

Javascript String escape character

Hi I have javascript string like this: let a = "\"2\" Kilogram" .

I want it to look like this a = "2 Kilogram" .

I have used unescape and str.replace but the response is like " "2" Kilogram" .

 let a = "\"2\" Kilogram"; a = data.replace(/\"/g, ""); console.log(a);

Replacing using regex will help you here as a pro.

\" is to be replaced and g is used as global iterator which will return only once all possibilities have been replaced.

You can simply replace the double quote like:

a = a.replace(/"/g, '')

Demo:

 let a = "\"2\" Kilogram" console.log("Before:", a) a = a.replace(/"/g, '') console.log("After:", a)

 let a = "\"2\" Kilogram"; console.log(a.replace(/"/g, ''))

You can use regex to replace \" like below

 let a = "\"2\" Kilogram" a = a.replace(/\"/g, "") console.log(a)

Hope this helps.

If you generelly want to remove all kind of special characters of the English language in a string and not only "" you may use:

 let string2replace = "\"2\" Kilogram"; var desiredstring = string2replace.replace(/[^\w\s]/gi, ''); alert(desiredstring);

a = a.slice(0, 2)+a.slice(3, a.length)+'"';

Or just use single quotes so the inner double quotes are not interpolated when you set the value a in the first place;)

let a ='"2 Kilogram";'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM