简体   繁体   中英

How to encode ' character in Javascript?

I have:

function showMessage(message) {
    alert(message);
}

But when the message comes dynamically from the server as(example): "Men's" it doesn't work.

I've tried:

function myEncode(message) {
    return message.replace("'", "\'");
}

showMessage(myEncode(message));

Doesn't seem to work. This is a simple example, the actual code is more complicated, but essentially this is the issue.

You should specify the g parameter, for a global replace (not only the first match).

You should also escape the slash:

function myEncode(message) {
    return message.replace(/'/g, "\\'");
}

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