I am currently working on a google chrome extension and I want to highlight the searched word.
I am highlighting by finding the match in innerHTML and adding "mark" tag around it. The problem is that when I do this if the searched word was used as a function name or tag name inside the HTML code also gets highlighted.
I want the innerHTML to work as innerText so that I could add tag around the matched word and the matched word won't be any elements of HTML code.
Can someone help me out in figuring this problem out, please?
I have this code so far:
var match = new RegExp(request + "(?![^<>]*>)", "gi");
document.documentElement.innerHTML = document.documentElement.innerHTML.replace(match, function (match) {
return ("<mark style='background-color: #FFFF99;'>" + match + "</mark>");
});
Related
I recently started learning/using about RegEx.
Is there a way to avoid matching words that are HTML tag attributes or belonging to tag attributes?
For example:
<p style=“position: absolute”>position: </p>
I tried
/\bposition\b\W\s/g
But that matches both instances.
Can I only match the second “position: “?
Clarification:
I am trying to search the document for words that the user enters and replace them with a span element containing those words - this is similar to "Ctrl + F". Simply having the text is not enough as I would need a way to also update the document once the text was replaced with the span elements.
Disclaimer: Use stuff like document.innerText and other DOM APIs rather than Regex.
Match HTML tags:
<.+?>/g
Match everything within HTML tags (should handle nested ones as well):
/(?<=<.+.>)(.*?)(?=<.*\/.+.?>)/g
https://regex101.com/r/2uZHli/ for example of the above.
The RegEx to match the HTML / XML tags is /(<([^>]+)>)/ig. Maybe be this is what you're looking for.
let str = '<p style="position: absolute">position: </p>';
const strWithoutTag = str.replace(/(<([^>]+)>)/ig, '');
console.log(strWithoutTag);
You can try the Regex to match your temp, which matched the second "position: ".
/(?=\b.*(?<yourKeyword>position).*\b)(?<=<[^]*>)([^<>]+)(?=<\/([^<>]*)>)/g
I am new to webDevelopment. I have a string , and I want to highlight some part of the strings like 10-15 things I want to highlight. Now I do have the offsets as well, like start and end of the text which I want to highlight from that string. SO, When in the loop first gets highlighted then it adds the span tag there with class mark, because of this the indexes are getting changed, then when it try to highlight the second then it does not get the perfect match because the offsets are now changed. So, How Can I match the exact text with the span tags or without that ?
$scope.highlight = function(content,startoffset,endoffset){return content.replace(content.substring(startoffset, endoffset), '<span class="' + className + '">$&</span>');}
.mark {background-colour = yellow;}
Can any please help me with this, This is really getting messy for me.
Refer this https://plnkr.co/edit/j5VCCjCHN60l0QNSTtLo?p=preview. I replaced your mark up with "**" as it is easy to show sample example.
function stringReplace(content, startoffset, endoffset, previousOffset) {
_temp = _temp.concat(content.substring(previousOffset || 0, startoffset));
_temp = _temp.concat('**');
}
I have to match a string that is not inside tags. I am working on projects that I don't have control over the back-end html rendering code. What I need to do is add a hover functionality for multiple dynamic words. I created a script that will look for those key words in specific elements and add their description in title tags for the hover. My problem is that if other keywords are found in other keyword's title tags.
My JS:
var str = 'match <span title="not match here">match</span> match';
str.replace( /match/gim, 'ok' );
I do not want the "match" word in the title attribute to be replaced, my desired result is:
'ok <span title="not match here">ok</span> ok'
how can I do that with Javascript?
I tried the expression below but it's not working for me:
^((?!(".+")match)*$
You need to capture tags first to be able to avoid them:
var result = str.replace(/(<[^>]*>)|match/gi, function (_,g1) {
return (g1==undefined)? 'ok':g1;
});
But if you can, using the DOM is probably the best way.
I am trying to change color of a part of strings. I have a list of DOM elements, and for each of them, the text can contain some hashtags. I would like to put in color all hashtags words which could be found in the text.
Here is the begin of the code :
var listOfText = document.getElementsByClassName("titleTweet");
for (var nodetext in listOfText) {
var divContent = listOfText[nodetext].innerHTML;
if (divContent.indexOf("#") !== -1) {
// Do job here
}
}
For example, divContent can be equals to "Hello my #friends ! How are you ?"
I would like to update the dom elements to put in red color the word "#friends".
I don't know how to do that using javascript or jQuery.
You can use a regexp to find the hastags and wrap them with html. Then use the .html() method to replace the original element's html with the new string.
Example snippet
$('#myDiv').replace(/#[a-z0-1A-Z]+/g, '<span style="color: red;">$&</span>'));
Working example - http://jsfiddle.net/4p4mA/1/
Edited the example to work on all divs on the page.
Note: This will only work so long as your element only contains text, because it is replacing all the child nodes with its text value.
use regex for this, find text having hashtag and replave that in span tag for each element.
$('.titleTweet').each(function(){
var $this=$(this);
$this.html($this.text()
.replace(/#[a-z0-1A-Z]+/g, '<span style="color: red;">$&</span>'));
});
See demo here
.innerHTML is a poor basis to starting replacing text. You'll want to navigate down to the text nodes and use .nodeValue to get the text. Then you can start splitting up the text nodes.
I am close to getting this function working, but not quite there yet.
The basic logic says find any p element that contains "+", strip the "+" from the text and try and replace the existing content with the new content and add a class.
Initially I had all of the matched elements being returned and concatenated into a single paragraph. So I tried to create an each function. I am now seeing the right results in the console, but I am not sure how to replace the content for the matched paragraph only (using $(this)).
I've made a fiddle here: http://jsfiddle.net/lharby/x4NRv/
Code below:
// remove bespoke text and add class
$qmarkText = $('.post p:contains("+")').each(function() {
$qStr = $(this).text().slice(1);
$qmarkText.replaceWith('<p class="subhead-tumblr"' + $qStr + '</p>');
console.log($qStr);
});
I know that $qmarkText is not quite but not sure how to fix this, have tried several variations.
Hopefully someone can help me out.
You could use following snippet:
// remove bespoke text and add class
$qmarkText = $('p').filter(function () {
return $(this).text().substring(0, 1) === "+"
}).each(function () {
$qStr = $(this).text().slice(1);
$(this).replaceWith('<p class="subhead-tumblr">' + $qStr + '</p>');
});
DEMO
This avoid using :contains() which will match even character '+' is inside content text, not only at the beginning.