admin管理员组文章数量:1397125
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
本文标签: JavaScriptjQuery escape special charsStack Overflow
版权声明:本文标题:JavaScriptjQuery escape special chars - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744146110a2592844.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论