While using jQuery's autocomplete, I've noticed that characters & and ' are
escaped as & and '
Example, autocomplete displays Barbara’s Straight Son but when I
choose this the field shows Barbara's Straight Son.
Any ideas how I can avoid this?
Thank you for your time!
you need to unescape the html entities. the easiest way i found to do that is to use this function:
var unescapeHtml = function (html) {
var temp = document.createElement("div");
temp.innerHTML = html;
var result = temp.childNodes[0].nodeValue;
temp.removeChild(temp.firstChild)
return result;
}
so pass your string through this function before it gets put into your input box. You might have to modify the autocomplete plugin in order to do this.
For example you can set label value in autocomplete using this code
var temp = document.createElement("pre"); // create new DOM element
temp.innerHTML = "Barbara's Straight Son" ; // set string which content HTML entities
return {
label: temp.firstChild.nodeValue, // get string from that DOM element which replace HTML entities to special character
value: "" // set your value here
}
Related
I think I have a string like:
href text, text, test
And I need to output
site/project/109# text, text, test
I can find all links
var txt = msg.match(/\<a\shref=\"(.*)\"\s(.*)[\<\/a\>]/gmi);
And in loop make replace. But I would like to shorten the code, do everything through single replace, like this :
var txt = msg.replace(/\<a\shref=\"(.*)\"\s(.*)[\<\/a\>]/gmi, $1);
But in this case I get: [object HTMLHeadElement]
Never use regex to parse HTML, it's better to generate an element with the content and do the rest on the element.
var str = 'href text, text, test';
// create an element
var temp = document.createElement('div');
// set the content with the string
temp.innerHTML = str;
// get all `a` tags and convert into array
// for older browser use `[].slice.call()
// for converting into array
Array.from(temp.querySelectorAll('a')).forEach(function(ele) {
// create a text node with the attribute value
var text = document.createTextNode(ele.getAttribute('href'));
// replace a tag wit the text node
ele.replaceWith(text);
});
// get the updated html content
console.log(temp.innerHTML)
Why not regex ? : RegEx match open tags except XHTML self-contained tags
UPDATE : The msg variable is an element object, a not string that's why it's getting converted to [object HTMLHeadElement](HTMLHeadElement refers to the HEAD tag, I think something wrong with your core check that also). So do the same as above where replace temp with the msg. In case you want to keep the original element content then generate temp element as above and set content as temp.innerHTML = msg.innerHTML .
If you're using jQuery (which is great and does all things) then you can get the href quite easily:
var string = 'href text, text, test';
var href = $(string).attr('href');
which means that setting the text of the anchor tag is trivial:
$(string).text($(string).href));
I'm writing a Firefox extension. I want to go through the entire plaintext, so not Javascript or image sources, and replace certain strings. I currently have this:
var text = document.documentElement.innerHTML;
var anyRemaining = true;
do {
var index = text.indexOf("search");
if (index != -1) {
// This does not just replace the string with something else,
// there's complicated processing going on here. I can't use
// string.replace().
} else {
anyRemaining = false;
}
} while (anyRemaining);
This works, but it will also go through non-text elements and HTML such as Javascript, and I only want it to do the visible text. How can I do this?
I'm currently thinking of detecting an open bracket and continuing at the next closing bracket, but there might be better ways to do this.
You can use xpath to get all the text nodes on the page and then do your search/replace on those nodes:
function replace(search,replacement){
var xpathResult = document.evaluate(
"//*/text()",
document,
null,
XPathResult.ORDERED_NODE_ITERATOR_TYPE,
null
);
var results = [];
// We store the result in an array because if the DOM mutates
// during iteration, the iteration becomes invalid.
while(res = xpathResult.iterateNext()) {
results.push(res);
}
results.forEach(function(res){
res.textContent = res.textContent.replace(search,replacement);
})
}
replace(/Hello/g,'Goodbye');
<div class="Hello">Hello world!</div>
You can either use regex to strip the HTML tags, might be easier to use javascript function to return the text without HTML. See this for more details:
How can get the text of a div tag using only javascript (no jQuery)
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.
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;
}
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>