-1

I'm trying to decode some specail characters in my string, before input it in HTML. But, for some reason, it didn't work. For ex:

My input string is "ampere 13th\'."

In JS I'm replacing every special character with this function:

htmlEntities: function(str) {
    return str.replace(/\\/g, "\").replace("'", "'").replace(".", ".").replace("%", "%").replace("\"",""");
},

But, when put it to HTML, it still looks like : "ampere 13th\'."

I want to show my data with replaced special characters.

What I'm doing wrong?

volodymyr3131
  • 335
  • 2
  • 5
  • 16
  • Possible duplicate of [Encode URL in JavaScript?](http://stackoverflow.com/questions/332872/encode-url-in-javascript) – ergonaut Oct 08 '15 at 11:57
  • It depends on how you put it into your HTML. `'` is the HTML entity for `'`, so placing `'` into HTML will render... guess what... `'`. – deceze Oct 08 '15 at 12:53
  • @deceze So, is it any way of put in html special sybmols lile I want to do it? Or it will alwayls be transformed? – volodymyr3131 Oct 08 '15 at 13:14
  • Again, it depends on how you insert the text. If you're using `innerHTML`, use `innerText` instead! Otherwise, escape the escape sequence to `'`. – deceze Oct 08 '15 at 13:24

1 Answers1

0

There is a single backslash in your string which is not being recognized as '\' but instead its an escape sequence. Other characters are being replace perfectly. I have written the following function which alerts the output string accordingly.

 function test() {
        var str = "ampere 13th\'.";
        alert(str.replace(/\\/g, "&#92").replace("'", "'").replace(".", ".").replace("%", "%").replace("\"", """));
    }

And it alerts me

ampere 13th'.

which is correct except replacing the '\' character. if you want to replace the '\' you can further search on how to replace a backslash character in java script.

if I have my input string like this

var str = "ampere 13th\\'.";

with two backslashes then the replacement occurs perfectly and my function alerts me

ampere 13th&#92'.
umer
  • 1,196
  • 1
  • 14
  • 33