How to insert HTML entities with createTextNode? - javascript

If I want to add an ascii symbol form js to a node somewhere?
Tried as a TextNode, but it didn't parse it as a code:
var dropdownTriggerText = document.createTextNode('blabla ∧');

You can't create nodes with HTML entities. Your alternatives would be to use unicode values
var dropdownTriggerText = document.createTextNode('blabla \u0026');
or set innerHTML of the element. You can of course directly input &...

createTextNode is supposed to take any text input and insert it into the DOM exactly like it is. This makes it impossible to insert for example HTML elements, and HTML entities. It’s actually a feature, so you don’t need to escape these first. Instead you just operate on the DOM to insert text nodes.
So, you can actually just use the & symbol directly:
var dropdownTriggerText = document.createTextNode('blabla &');

I couldn't find an automated way to do this. So I made a function.
// render HTML as text for inserting into text nodes
function renderHTML(txt) {
var tmpDiv = document.createElement("div"); tmpDiv.innerHTML = txt;
return tmpDiv.innerText || tmpDiv.textContent || txt;
}

Related

JS. How do I replace text in the html () object within a variable?

Using JS I copied html code into variable.
html_block = $(".first-prj-container").html();
In some places it is necessary to make a replacement for the text. This can be either plain text or class names, IDs. Is it possible to make replacement via strReplace, and then append the result into the page like this:
$("#all-prj-container").append(html_block);
Try this:
let htmlToReplace = $(".first-prj-container").prop('outerHTML')
let updatedHtml = htmlToReplace.replace('hi', 'hello')
$("#all-prj-container").append(updatedHtml);
See more here outerHTML - MDN
you can also use regEx to refine your filter for white spaces, case sensitivity, or filter for certain nested tags:
let updatedHtml= $(".first-prj-container")
.innerHTML.toLowerCase() //make case-insensitive, can also be done with regEx "i"
.replace(/\s/g,'') //remove white spaces
.replace("(hi)(?!(.(?!<h1))*?</h1>)", "hello"); //skip h1 tag content
$(".first-prj-container").innerHTML = updatedHtml;

How to get text from tags, trimm, and paste to tags again in javascript

I would like to trimm text from html tags, and paste result to these tags again. It's not DOM content, only string.
var string = "<div class='someClass'><b>Some very long text</b></div>"
Wanted result is f.e.:
var string = "<div class='someClass'><b>Some very lon</b></div>"
I found library striptags, but it only gets rid off tags, but I want to keep them.
If you have any solution please let me know :)
UPDATE:
Thanks all of you for advices. There are few things to add from me: 1. I never have information about html tags, because it came from quill text editor, and I need some kind of regex. 2. In my job there is no jQuery, it's kind of 'evil' :P. 3. I'm using react, so any use of 'document' or 'window' is unwanted here :(.
Checkout trim() method of javascript or String.prototype.trim().
Hope it will work for you!
If it is a string and you want to trim some portion of text. you can use the substring/slice function of javascript.
For more refernce you can refer below links
http://www.w3schools.com/jsref/jsref_substring.asp
http://www.w3schools.com/jsref/jsref_slice_string.asp
You could use a hidden tag where you manipulate the string. Something like
<div id="tags-modifier" ></div>
and then jquery like like
var string = "<div class='someClass'><b>Some very long text</b><b>Test2213213213213</b></div>"
$("#tags-modifier").html(string);
var part= 5;
$.each($('#tags-modifier *:not(:has("*"))'), function(){
mytext=$(this).html()
$(this).html(mytext.substring(0, part))
})
string = $("#tags-modifier").html();
This works even if there are multiple siblings
Fiddle here
If the structure is exact like you showed <div class='someClass'><b>Some very long text</b></div>, you could do it with regex to find the text, and in the function change it how you like, shorten(substr)/trim/...:
var longText ="<div class='someClass'><b>Some very long text</b></div>";
const MAX_LENGTH = 13;
// regex expression matches the structure given
var shortText = longText.replace(/(<div[^>]+><b>)([^<]+)(?=<\/b><\/div>)/gi, function(m1,m2,m3){
// m2 matches "<div class='someClass'><b>"
// m3 matches "Some very long"
return m2 + m3.substr(0, MAX_LENGTH).trim();
})
console.info(shortText)
Here some documentation to the replace function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
A "cooler" Alternative:
If you pass the HTML Element that should be altered, to this short function checkChildren, all Child-Textnodes will be modified, trim, substr, ...
(it is a bit of an overkill, checking every node, if you know the final structure, but i just wanted to test it):
var elem = document.getElementById("test");
//define the max length of text nodes
const MAX_LENGTH = 13;
checkChildren(elem);
// check all children from parent element an limit the size of textNodes
function checkChildren(parent){
for(var i=0; i<parent.childNodes.length;i++){
var child = parent.childNodes[i];
switch(child.nodeType){
case Node.ELEMENT_NODE:
// recursive call
checkChildren(child);
break;
case Node.TEXT_NODE:
// modify textNode (Shorten and trim)
child.nodeValue = child.nodeValue.substr(0,MAX_LENGTH).trim();
break;
}
}
}
<div id="test" class='someClass'><b>Some very long text</b></div>
You can use $.parseHTML to convert this string into dom tree. Get the <b> node from this dom tree and change the text with the help of substr.

How to remove only html tags in a string using javascript

I want to remove html tags from given string using javascript. I looked into current approaches but there are some unsolved problems occured with them.
Current solutions
(1) Using javascript, creating virtual div tag and get the text
function remove_tags(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent||tmp.innerText;
}
(2) Using regex
function remove_tags(html)
{
return html.replace(/<(?:.|\n)*?>/gm, '');
}
(3) Using JQuery
function remove_tags(html)
{
return jQuery(html).text();
}
These three solutions are working correctly, but if the string is like this
<div> hello <hi all !> </div>
stripped string is like
hello . But I need only remove html tags only. like hello <hi all !>
Edited: Background is, I want to remove all the user input html tags for a particular text area. But I want to allow users to enter <hi all> kind of text. In current approach, its remove any content which include within <>.
Using a regex might not be a problem if you consider a different approach. For instance, looking for all tags, and then checking to see if the tag name matches a list of defined, valid HTML tag names:
var protos = document.body.constructor === window.HTMLBodyElement;
validHTMLTags =/^(?:a|abbr|acronym|address|applet|area|article|aside|audio|b|base|basefont|bdi|bdo|bgsound|big|blink|blockquote|body|br|button|canvas|caption|center|cite|code|col|colgroup|data|datalist|dd|del|details|dfn|dir|div|dl|dt|em|embed|fieldset|figcaption|figure|font|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|header|hgroup|hr|html|i|iframe|img|input|ins|isindex|kbd|keygen|label|legend|li|link|listing|main|map|mark|marquee|menu|menuitem|meta|meter|nav|nobr|noframes|noscript|object|ol|optgroup|option|output|p|param|plaintext|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|source|spacer|span|strike|strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|track|tt|u|ul|var|video|wbr|xmp)$/i;
function sanitize(txt) {
var // This regex normalises anything between quotes
normaliseQuotes = /=(["'])(?=[^\1]*[<>])[^\1]*\1/g,
normaliseFn = function ($0, q, sym) {
return $0.replace(/</g, '<').replace(/>/g, '>');
},
replaceInvalid = function ($0, tag, off, txt) {
var
// Is it a valid tag?
invalidTag = protos &&
document.createElement(tag) instanceof HTMLUnknownElement
|| !validHTMLTags.test(tag),
// Is the tag complete?
isComplete = txt.slice(off+1).search(/^[^<]+>/) > -1;
return invalidTag || !isComplete ? '<' + tag : $0;
};
txt = txt.replace(normaliseQuotes, normaliseFn)
.replace(/<(\w+)/g, replaceInvalid);
var tmp = document.createElement("DIV");
tmp.innerHTML = txt;
return "textContent" in tmp ? tmp.textContent : tmp.innerHTML;
}
Working Demo: http://jsfiddle.net/m9vZg/3/
This works because browsers parse '>' as text if it isn't part of a matching '<' opening tag. It doesn't suffer the same problems as trying to parse HTML tags using a regular expression, because you're only looking for the opening delimiter and the tag name, everything else is irrelevant.
It's also future proof: the WebIDL specification tells vendors how to implement prototypes for HTML elements, so we try and create a HTML element from the current matching tag. If the element is an instance of HTMLUnknownElement, we know that it's not a valid HTML tag. The validHTMLTags regular expression defines a list of HTML tags for older browsers, such as IE 6 and 7, that do not implement these prototypes.
If you want to keep invalid markup untouched, regular expressions is your best bet. Something like this might work:
text = html.replace(/<\/?(span|div|img|p...)\b[^<>]*>/g, "")
Expand (span|div|img|p...) into a list of all tags (or only those you want to remove). NB: the list must be sorted by length, longer tags first!
This may provide incorrect results in some edge cases (like attributes with <> characters), but the only real alternative would be to program a complete html parser by yourself. Not that it would be extremely complicated, but might be an overkill here. Let us know.
var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");
Here is my solution ,
function removeTags(){
var txt = document.getElementById('myString').value;
var rex = /(<([^>]+)>)/ig;
alert(txt.replace(rex , ""));
}
I use regular expression for preventing HTML tags in my textarea
Example
<form>
<textarea class="box"></textarea>
<button>Submit</button>
</form>
<script>
$(".box").focusout( function(e) {
var reg =/<(.|\n)*?>/g;
if (reg.test($('.box').val()) == true) {
alert('HTML Tag are not allowed');
}
e.preventDefault();
});
</script>
<script type="text/javascript">
function removeHTMLTags() {
var str="<html><p>I want to remove HTML tags</p></html>";
alert(str.replace(/<[^>]+>/g, ''));
}</script>

find text wrapped in brackets in jQuery

I have some text on a page and I want to located and remove any text found in brackets.
For example:
<td>here is [my text] that I want to look at</td>
So I want to grab that text (my text), save it in a variable and remove it from where it is.
If you're using jQuery you could use a regular expression like \[(.+)\] on $('body').text().
EDIT: Sorry, I might have jumped the gun a little bit giving you this answer. Going to think about it for a few more minutes and try to update this with a little more info.
You may find that this task is not all that simple. If you have control over the text before it is sent to the web browser you may want to put a <span class='bracket'>[my text]</span> around the text, then you could easily do something like this with jQuery:
$(".bracket").each(function() {
// store the data from $(this).text();
}).remove();
This can be done using regular expressions and jQuery, but there are problems that may creep up dealing with text inside of attributes like <input name='test[one][]' /> The "simple" regex would be to do something like this:
$("td").each(function() {
var $this = $(this);
var html = $this.html();
var bracketText = [];
// match all bracketed text in the html - replace with an empty string
// but push the text on to the array.
html = html.replace(/\[([^\]]+)\]/g, function() {
bracketText.push(arguments[1]);
return "";
});
// put the new html in away and save the data for later
$this.html(html).data("bracketText", bracketText);
});
There is not much danger in doing this if you're sure you wont have [] inside of tags other than in the text.
I ended up doing the following:
$('#formQuizAnswers td.question').each(function(){
var header = $(this).text().match(/-.*-/);
$(this).text($(this).text().replace(header,''));
});
I changed my text I search for to have dashes around it IE -My text-

Is there a getElementsByTagName() like function for javascript string variables?

I can use the getElementsByTagName() function to get a collection of elements from an element in a web page.
I would like to be able to use a similar function on the contents of a javascript string variable instead of the contents of a DOM element.
How do I do this?
EDIT
I can do this by creating an element on the fly.
var myElement = new Element('div');
myElement.innerHTML = "<strong>hello</strong><em>there</em><strong>hot stuff</strong>";
var emCollection = myElement.getElementsByTagName('em');
alert(emCollection.length); // This gives 1
But creating an element on the fly for the convenience of using the getElementsByTagName() function just doesn't seem right and doesn't work with elements in Internet Explorer.
Injecting the string into DOM, as you have shown, is the easiest, most reliable way to do this. If you operate on a string, you will have to take into account all the possible escaping scenarios that would make something that looks like a tag not actually be a tag.
For example, you could have
<button value="<em>"/>
<button value="</em>"/>
in your markup - if you treat it as a string, you may think you have an <em> tag in there, but in actuality, you only have two button tags.
By injecting into DOM via innerHTML you are taking advantage of the browser's built-in HTML parser, which is pretty darn fast. Doing the same via regular expression would be a pain, and browsers don't generally provide DOM like functionality for finding elements within strings.
One other thing you could try would be parsing the string as XML, but I suspect this would be more troublesome and slower than the DOM injection method.
function countTags(html, tagName) {
var matches = html.match(new RegExp("<" + tagName + "[\\s>]", "ig"));
return matches ? matches.length : 0;
}
alert(
countTags(
"<strong>hello</strong><em>there</em><strong>hot stuff</strong>",
"em"
)
); // 1
var domParser = new DOMParser();
var htmlString = "<strong>hello</strong><em>there</em><strong>hot stuff</strong>";
var docElement = domParser.parseFromString(htmlString, "text/html").documentElement;
var emCollection = docElement.getElementsByTagName("em");
for (var i = 0; i < emCollection.length; i++) {
console.log(emCollection[i]);
}
HTML in a string is nothing special. It's just text in a string. It needs to be parsed into a tree for it to be useful. This is why you need to create an element, then call getElementsByTagName on it, as you show in your example.

Categories

Resources