I need to escape a String with special characters and i dont know how to do that.
The String var value is set by an Input field, so the user can write any special character as he wants, even the ones that i dont know and i could break the syntax...so instead of escape char by char, i want to know what's the better method to acplish this.
This is my example code:
string = '-|{}?" Hello \$#^*&@)(~';
newHTML= '<span class="color-red"><b>'+string+'</b></span>';
$('#my-div').append(newHTML);
But i get a syntax error.I want to escape all special characters... as you can see this code detector also is not working when i use ' in the string
I need to escape a String with special characters and i dont know how to do that.
The String var value is set by an Input field, so the user can write any special character as he wants, even the ones that i dont know and i could break the syntax...so instead of escape char by char, i want to know what's the better method to acplish this.
This is my example code:
string = '-|{}?" Hello \$#^*&@)(~';
newHTML= '<span class="color-red"><b>'+string+'</b></span>';
$('#my-div').append(newHTML);
But i get a syntax error.I want to escape all special characters... as you can see this code detector also is not working when i use ' in the string
Share Improve this question edited Jan 17, 2016 at 1:44 xnanitox asked Jan 17, 2016 at 1:36 xnanitoxxnanitox 4951 gold badge6 silver badges9 bronze badges 3- What is the syntax error you're getting? You can escape characters in javascript by using the `\` character – mwilson Commented Jan 17, 2016 at 1:41
- Just use the built in text() method in jquery this encodes the string before adding it to an element. In my answer I used that behaviour as a trick to encode the string :D – seahorsepip Commented Jan 17, 2016 at 1:46
- Also jquery encodes the quotes already when fetching a value from an input element, otherwise jquery would already error by itself when asking to alert a input element value with a quote in it... – seahorsepip Commented Jan 17, 2016 at 1:52
2 Answers
Reset to default 5Or easy jQuery trick:
string = $("<div></div>").text(string).html();
text() encodes the string inside the temporary div and html() fetches the encoded string :)
You used escape character(backslash) \
in string. You must use escape character before the escape character in order to escape it.
So you must define this character in your string like : \\
You see, every special character in c based programming/scripting languages, must be used with escape character. Like newline or return. \n \r