REMOVE HTML SPECIAL CHARACTERS FROM STRING JAVASCRIPT

Does any one know how lớn convert special characters to HTML in Javascript?

Example:

& (ampersand) becomes &. " (double quote) becomes " when ENT_NOQUOTES is not mix. " (single quote) becomes ' only when ENT_QUOTES is phối. < (less than) becomes <. > (greater than) becomes >.
see also: obatambeienwasirherbal.com/questions/1354064 – Chris Jan 21 "13 at 19:30
You can use this library: npmjs.com/package/utf8 – Camilo Ortegón May 15 "17 at 18:35

You need a function that does something like

return mystring.replace(/&/g, "&").replace(/>/g, ">").replace(/But taking inlớn trương mục your desire for different handling of single/double quotes.

Bạn đang xem: Remove html special characters from string javascript


what does the slash g do? – JohnnyBizzle Jun 20 "16 at 11:29

JohnnyBizzle /g in a regular expression means "global". Simply put, all occurrences of the string will be replaced. Without /g only the first match would be replaced. – Kevin G. Jul 21 "16 at 11:42


The best way in my opinion is khổng lồ use the browser"s inbuilt HTML escape functionality to lớn handle many of the cases. To bởi this simply create a element in the DOM tree and set the innerText of the element lớn your string. Then retrieve sầu the innerHTML of the element. The browser will return an HTML encoded string.

function HtmlEncode(s)

Test run:

alert(HtmlEncode("&;"><""));

Output:

&;"><"

This method of escaping HTML is also used by the Prototype JS library though differently from the simplistic sample I have given.

Note: You will still need to escape quotes (double and single) yourself. You can use any of the methods outlined by others here.


note that delete el is a mistake here. perfectionkills.com/understanding-delete – gblazex Oct 7 "11 at 20:49
This doesn't bởi anything for me when I try it. I get the characters back unchanged. – Moss Oct 12 "11 at 17:17

Sorry, I was testing with odd characters, plus Chrome is sneaky and doesn't show you the real HTML output, but Firebug does (actually it showed an html entity for the copyright symbol when the generated source doesn't encode it). This does work fine on <>& but isn't as all encompassing as Neotropic's or KooiInc's solutions. – Moss Oct 12 "11 at 17:35

with jQuery, output = $('
').text(input).html() – rồng Mar 17 "12 at 22:54

Both methods does not convert ' inlớn ' và " into " So it still can be used for XSS attacks. – Sometoàn thân Jul 2 "12 at 10:15


This generic function encodes every non alphabetic character khổng lồ its htmlcode (numeric):

function HTMLEncode(str) else } return aRet.join(""); }
This sounds really clever but I can only get it to lớn convert the basics: <>& – Moss Oct 12 "11 at 17:53
nvm. It runs in a console fine, but when you output to lớn the browser it looks lượt thích it hasn't converted stuff. What is up with that? – Moss Oct 12 "11 at 17:57
Moss: the browser renders the htmlencoded characters khổng lồ the characters they represent. The advantage of html-encoded characters is that a browser doesn't have lớn guess about the translation of (e.g.) diacritical characters và thus always renders those characters like they should be rendered. – KooiInc Oct 13 "11 at 6:34
You might consider changing this lớn remove sầu the array-like access off of str. IE7 and below don't support that, & you can just as easily Hotline charCodeAt right off of str with i as the argument. var iC = str.charCodeAt(i) – Chase Jan 30 "12 at 7:54
This code is not producing the correct HTML Entity value for the ± character which should be ± but it is returning � which is an unknown character �. – Paul Atruyền thông quảng cáo 25 "14 at 17:03


From Mozilla ...

chú ý that charCodeAt will always return a value that is less than 65,536. This is because the higher code points are represented by a pair of (lower valued) "surrogate" pseudo-characters which are used khổng lồ comprise the real character. Because of this, in order lớn examine or reproduce the full character for individual characters of value 65,536 & above sầu, for such characters, it is necessary to retrieve sầu not only charCodeAt(i), but also charCodeAt(i+1) (as if examining/reproducing a string with two >letters).

Xem thêm: Tổng Hợp: 3 Cách Làm Sốt Bò Bít Tết Siêu Ngon Như Đầu Bếp 5 Sao

The Best Solution

/** * (c) 2012 Steven Levithan * MIT license */ if (!String.prototype.codePointAt) return code; }; } /** * Encodes special html characters *

return */ function html_encode(string) else } return ret_val; }

Usage example:

html_encode("✈");
I was facing issue with only single quotes( ') & double quotes (") in my đầu vào value khổng lồ display in html. Script was breaking if user add it. – Dharam Mali Aug 2 "16 at 5:24


For those who want khổng lồ decode an integer char code like &#xxx; inside a string, use this function:


function decodeHtmlCharCodes(str) ); } // Will output "The show that gained int’l reputation’!" console.log(decodeHtmlCharCodes("The show that gained int’l reputation’!"));

const decodeHtmlCharCodes = str => str.replace(/(&#(d+);)/g, (match, capture, charCode) => String.fromCharCode(charCode)); // Will output "The show that gained int’l reputation’!" console.log(decodeHtmlCharCodes("The show that gained int’l reputation’!"));
This should be the accepted answer as this will decode everything. – Quesofat Jul 15 "19 at 23:04
This is the answer I was looking for. Thanks. – Dzenis H. May 17 "20 at 16:25
This works great., But for some reason when mixed in with some JQuery Functionality, it misfires. Sometimes does inkhổng lồ convert some, or only a couple. But in general, works great. onBlur="char_convert(this);" – Neotropic Jan 3 "11 at 16:34
Uh, I get an error "Uncaught TypeError: Cannot điện thoại tư vấn method 'replace' of undefined" in Chrome và "arguments.value is undefined" in Firebug. – Moss Oct 12 "11 at 17:52
putting all of those special characters into an array like that is completely pointless. see other answers. – Gavin Aug 15 "13 at 20:41
Best solution for me, the only one that converts í khổng lồ í for example. – Edhowler May 8 "18 at 17:55
How vị you get those chars from your keyboard? I know this is a silly question butt...in OS X for example – PositiveGuy Jun 22 "đôi mươi at 21:59


As was mentioned by rồng the cleanest way lớn bởi vì it is with jQuery:

function HtmlEncode(s) function HtmlDecode(s)
Interesting, but if your string contains a space, this won't alter it. A better way is lớn use encodeURI(yourString); – Mike Gledhill Nov 28 "14 at 10:07


function ConvChar( str ) ; return str.replace( /<<&>""#>/g, function(s) ); } alert( ConvChar("<-"-&-"->-<-"-#-"->") );

Result:

<-"-&amp;-"->-<-'-#-'->

In testarea tag:

<-"-&-"->-<-"-#-"->

If you"ll just change a little chars in long code...


In a PRE tag -& in most other HTML tags- plain text for a batch file that uses the output redirection characters (< và >) will break the HTML, but here is my tip: anything goes in a TEXTAREA element -it will not break the HTML, mainly because we are inside a control instanced và handled by the OS, and therefore its nội dung are not being parsed by the HTML engine.

As an example, say I want lớn highlight the syntax of my batch file using javascript. I simply paste the code in a textarea without worrying about the HTML reserved characters, and have sầu the script process the innerHTML property of the textarea, which evaluates lớn the text with the HTML reserved characters replaced by their corresponding ISO-8859-1 entities.

Browsers will escape special characters automatically when you retrieve the innerHTML (và outerHTML) property of an element. Using a textarea (& who knows, maybe an input đầu vào of type text) just saves you from doing the conversion (manually or through code).

I use this triông xã lớn kiểm tra my syntax highlighter, & when I"m done authoring and testing, I simply hide the textarea from view.