Javascript / jQuery: How to convert string to HTML character code [duplicate] - javascript

This question already has answers here:
How to convert characters to HTML entities using plain JavaScript
(12 answers)
Closed 8 years ago.
I have a string that contains text including special characters like apostrophes, quotes, ampersand etc. that I would like to convert to HTML character codes, e.g. to show &#39 instead of an apostrophe etc. (as per the following list: http://www.w3.org/MarkUp/html-spec/html-spec_13.html.
I do not necessarily need to convert letters and spaces as long as the above and some other basic characters are encoded correctly.
For a temporary workaround I use simple replaces like str = str.replace("'", "&#39") but would like to avoid this as it only covers certain characters.
I was thinking of encodeURI or encodeURIcomponent but would like to know what is the best and easiest way to achieve this without encoding more than necessary.
Can someone tell what is the best way here if the idea is to avoid any issues with other JS where this is inserted dynamically, esp. thinking of single quotes, double quotes and any other character that could cause issues here (referring to JavaScript / jQuery and English language only) ?

function encodeEntities(value) {
return $('<div />').text(value).html();
}

Related

inconsistent behaviour in jQuery selector [duplicate]

This question already has answers here:
How to select html nodes by ID with jquery when the id contains a dot?
(8 answers)
Closed 5 years ago.
$('#a.b') // doesn't work
document.getElementById('a.b') // works
$('[id="a.b"]') // works
Can anyone explain why $('#a.b') doesn't work.
Do not use meta characters in your Id's while using Jquery.
. is a meta character and selector see them as regex. You need to escape to make it work. For ex \\.
In this case -
$('#a\\.b')
Javascript getElementById also works because, for it, it's just a String.
When you giving as id="a.b" it checks for a value and won't get treated as meta character.
jQuery thinks it is a class. So, you write it using escape sequence as -
$('#a\\.b')
You should use the escaping operator as follows:
$('#a\\.b')
jQuery does not allow meta-characters as a literal part of a name, and those must be escaped with two backslashes \\.

matching regex ignoring whitespace and new lines [duplicate]

This question already has answers here:
Why it's not possible to use regex to parse HTML/XML: a formal explanation in layman's terms
(10 answers)
Closed 6 years ago.
I have an xml string that looks something like
<parent><child>value</child></parent>
I’m trying to write a regular expression that matches this string. Trick is, sometimes the input has random new lines and spaces in it.
For example:
<parent>
<child>value</child></parent>
I’d like to be able to identify using regex if the input xml has a parent, child and value.
So far I’ve tried:
“<parent>\n\s*<child>value<\/child>”
But this doesn’t seem to match. I don’t understand how to ignore ALL whitespace and ALL new lines in my expression.
SOLUTION:
So when you are working with older systems, in healthcare tools for example you may often need to match xml requests and it's very much possible... through trial and error here's what worked for me:
^<parent>\s*<child>value[\S\s]*
You should not parse XML with a regular expression. Instead use an XML parser, which is available in JavaScript:
var sMyString = '<parent><child>value</child></parent>';
var oDOM = new DOMParser().parseFromString(sMyString, "text/xml");
var txt = oDOM.documentElement.textContent;
console.log(txt);
This parser knows how to deal with white space. Note that white space can also occur in the tags, like <parent >

Strip tags from a string - HTML5 [duplicate]

This question already has answers here:
Remove HTML Tags in Javascript with Regex
(13 answers)
Closed 7 years ago.
The following string is valid HTML in HTM5, even with the > in the attribute:
'<span src="whatever.png" data-info="hello>there">text</span>';
Almost all solutions proposed before use a variant of:
replace( /<.*?>/g, '' )
Which fails for this due to the > in the attribute.
There is also the option of writing the content to a dummy element and then reading back the textContent, but that is horribly slow when dealing with a lot of data.
So, I was wondering if anyone has any suggestions? Removing the attributes - or at least the attribute values with the matching quotes in a first pass regex and then a second pass to strip the tags seems like it might be the way to go, but I can't quite get my head around it!
I believe this regex should work for your purpose:
/<([^\"\'>]*|\"([^"\\]|\\.)*\"|\'([^'\\]|\\.)*\')*>/g
Essentially, it matches any character other than ", ' or >, or it matches " or ' followed by any characters followed by another " or '.
Just use it in the same way as you did in the original question - string.replace(/<([^\"\'>]*|\"([^"\\]|\\.)*\"|\'([^'\\]|\\.)*\')*>/g, '');

Can single quotes and double quotes be used interchangeably while enclosing strings in javascript? [duplicate]

This question already has answers here:
Are double and single quotes interchangeable in JavaScript?
(23 answers)
Closed 8 years ago.
Till now whatever programming languages I have encountered use double quotes for string and single quotes for characters but some of the javascript code that I saw seemed to be using them interchangeably,is it possible?
In which situations can they be interchanged?
In which situations they CANNOT be interchanged?
They are interchangeable, but when you open a string with one, you must close it with the same character. For instance,
"Hello' would not be a valid string.
EDIT: PS, this allows for you to enclose quotes in a string. For example, if you want to have the string literal "Hello", you could have
var string = '"Hello"'
yes they can as long as you keep in mind a few main things;
1- double quotes are the preferred by the browser to se they parameters values, so you never use them when setting javascript values or function calls within the DOM.
2- double quotes are also used to specify json an properties a json string using single quotes to delimiter they key, value pairs is not valid.
3-they don't complement each other, so what one starts one must end.
4 - if you need to use the same quote inside your string you need to scape it.

Why should we use ' instead of " for Strings in Javascript [duplicate]

This question already has answers here:
Are double and single quotes interchangeable in JavaScript?
(23 answers)
Closed 8 years ago.
If often heard that I should declare String in Javascript in ' (single quotation marks) instead of " (double quotation marks) like in Java or other languages.
Unfortunately did i never ask why to do that.
The "best" answer I got until now was
It's more performant
Is that true? And why?
In many languages using '' instead of "" is more performant because in string denoted by single quotes substitutions of escaped chars are not performed. This is not true in js. The reason there is a double quotation system, as far as I know, is that it allows you to avoid escaping "" in strings while using ''. Then it's a matter of taste.
One reason might be the fact that it's more possible to need to use " in strings than '. So it's a good idea to use single quote to indicate a string literal, and save double quote to use inside the string.
For example in HTML the attribute of a value must be placed in double quotes like: <div class="myClass">.
so if you're creating such things dynamically you might need to use " in your string generation.

Categories