RegEx Search & Heighlight using jQuery/JavaScript - javascript

What I am looking for:
When I search for "em" in my search field it should highlight only containing "Em" at starting of any word. And when I search for "Em*" in my search it should highlight "Empty, Emailing, Email" etc.
now that working with my code but not in single sentence or 'p' tag. It only works with different 'p' or 'div' or line though I added "gim" in RegEx and case insensitive also doesn't work ether. Here is my code working sample: http://jsfiddle.net/rameshbaddi/3w3tw/15/
var searchPattern2 = new RegExp("(" + searchTerm + ")", "gmi");
for (var i = 0; i < strArray.length; i++) {
if (strArray[i].match(searchPattern2)) {
var replaceValue2 = "<span class='" + highlightClass + "'>" + searchTerm + "</span>";
alert(searchPattern2);
var tempNode2 = document.createElement('span');
tempNode2.innerHTML = node.nodeValue.replace(searchTerm, replaceValue2);
node.parentNode.replaceChild(tempNode2, node);
}
}
}

Related

JavaScript: Code says "cannot read property 'indexOf' of undefined" but I can't fix the problem

The code is used in a HTML document, where when you press a button the first word in every sentence gets marked in bold
This is my code:
var i = 0;
while(i < restOftext.length) {
if (text[i] === ".") {
var space = text.indexOf(" ", i + 2);
var tekststykke = text.slice(i + 2, space);
var text = text.slice(0, i) + "<b>" + tekststykke + "</b>" + text.slice(i + (tekststykke.length + 2));
var period = text.replace(/<b>/g, ". <b>");
var text2 = "<b>" + firstWord + "</b>" + period.slice(space1);
i++
}
}
document.getElementById("firstWordBold").innerHTML = text2;
}
It's in the first part of the code under function firstWordBold(); where it says there is an error with
var space1 = text.indexOf(" ");
Looks like you're missing a closing quote on your string, at least in the example you provided in the question.
Your problem is the scope of the text variable. In firstWordBold change every text to this.text, except the last two where you re-define text
Also, if you want to apply bold to the first word this is easier...
document.getElementById('test-div-2').innerHTML = '<b>' + firstWord + '</b>' + restOftext;
It now works for me, with no errors and it applies bold to the first word.
Here's how the function ended up,
function firstWordBold() {
console.log('bolding!');
var space1 = this.text.indexOf(' ');
var firstWord = this.text.slice(0, space1);
var restOftext = this.text.slice(space1);
document.getElementById('test-div-2').innerHTML = '<b>' + firstWord + '</b>' + restOftext;
}
To make every first word bold, try this...
function firstWordBold() {
let newHTML = '';
const sentences = this.text.split('.');
for (let sentence of sentences) {
sentence = sentence.trim();
var space1 = sentence.indexOf(' ');
var firstWord = sentence.slice(0, space1);
var restOftext = sentence.slice(space1);
newHTML += '<b>' + firstWord + '</b>' + restOftext + ' ';
}
document.getElementById('test-div-2').innerHTML = newHTML;
}
One last edit, I didn't notice you had sentences ending with anything other that a period before. To split on multiple delimiters use a regex, like so,
const sentences = this.text.split(/(?<=[.?!])\s/);

Javascript RegExp parsing IRC color codes

I'm trying to parse IRC color codes in the format \u00030 to \u000315.
I added all RGB colors to a table, and looping through them I with this:
console.log(i + ">" + '\\u0003'+i + ">" + colors[i]);
var re = new RegExp("\\u0003"+i, 'gi');
console.log(re + " > " + '</span><span style="color:' + colors[i]+ ';">');
I get this output:
tools.php:337 15>\u000315>rgb(210,210,210)
tools.php:339 /\u000315/gi > </span><span style="color:rgb(210,210,210);">
tools.php:337 14>\u000314>rgb(127,127,127)
tools.php:339 /\u000314/gi > </span><span style="color:rgb(127,127,127);">
tools.php:337 13>\u000313>rgb(255,0,255)
tools.php:339 /\u000313/gi > </span><span style="color:rgb(255,0,255);">
tools.php:337 12>\u000312>rgb(0,0,252)
And nothing changes when I do html.replace(re, "<span stuff>");
Hardcoding it down to html.replace(/\\u00314/gi, '</span><span style="color: rgb(127,127,127);">'); produces no results either..
The stuff I'm trying to parse:
\u0002\u000314:: \u00037Channel Name \u000314:: \u00030SITE: \u00034UP \u000314:: \u00030IRC BONUS: \u00034OFFLINE \u000314:: \u00030SIGNUPS: \u00034CLOSED \u000314::\u000f
I seem to be missing something. \u or \\u makes no difference, gi, g, i or none makes no difference, and all in all it seems like it's simply not parsing anything this way.
The thing I did find out is that if I drop the RegExp and thus the modifiers for just html.replace("\\u00314", '</span><span style="color: rgb(127,127,127);">'); it replaces the first occurence, but that's not enough.
Is there something obvious I'm missing?
What worked in the end is the code below. Saving the string to a variable rather than doing the +i in the function is what worked
var val = $('textarea#topic').val();
var html = "<span style=\"color: #fff;\">" + val + "</span>";
var colors = [
"rgb(0,147,0)",
"rgb(0,0,0)",
"rgb(0,0,127)",
"rgb(0,147,0)",
"rgb(255,0,0)",
"rgb(127,0,0)",
"rgb(156,0,156)",
"rgb(252,127,0)",
"rgb(255,255,0)",
"rgb(0,252,0)",
"rgb(0,147,147)",
"rgb(0,255,255)",
"rgb(0,0,252)",
"rgb(255,0,255)",
"rgb(127,127,127)",
"rgb(210,210,210)"
];
for(i = (colors.length-1); i >= 0; i--) {
var index = 0;
var str = "\\u0003"+i+"";
while((index = html.indexOf(str, index + 1)) > -1) {
html = html.replace(str, '</span><span style="color:' + colors[i]+ ';">');
console.log(str + ">" + colors[i]);
}
$('div#topictext').html(html);
done = false;
setTimeout(setTrue(), 5000);
while(!done) {
}
}
html = html.replace("\\u0002", "");
html = html.replace("\\u000f", "");
$('div#topictext').html(html);

javascript regex to capture word in an html text

I'm explaining my issue.
I'm trying to do a javascript function to highlight words (change their color) in an html text. I have another function to un highlight them.
I have a list of keywords that i have to highlight.
Here is the code i've writed so far
function highlight_words(keywords) {
unHighlight_words(keywords);
$('.rubricContent').each(function(index, element) {
//get elements for each rubrics
var content = $(element).html();
if (keywords) {
$(keywords).each(function(i, e) {
var term = e
var re = new RegExp('(?:[^.;\w]|^|^\\W+){0}('+ term + ' )(?:[^.\w]|\\W(?=\\W+|$)|$){0}', "gmi");
var subst = '<span style="color:red">' + term + '</span> ';
content = content.replace(re, subst);
});
$(element).html(content);
}
});
The result is not that bad my words are red colored but not when they are followed by a "." or a ","
Anyone have the solution for me ?
Thanks !!
You can use \b word boundary as follows.
term='Test';
content='TestTest. Test Test: Test. Test, TESTtest'
var re = new RegExp('(\\b'+term+'\\b)', "gmi");
var subst = '<span style="color:red">' + term + '</span> ';
content = content.replace(re, subst);
alert(content)
https://jsfiddle.net/3royvd66/1/

How to reference found matches?

I'm having a small problem with a regexp pattern. I don't have regexp knowledge, so I couldn't solve it.
I have this text:
var text = "this (is) some (ran)dom text";
and I want to capture anything between (). So after following this tutorial I came up with this pattern:
var re = /(\(\w*\))/g;
which works fine. But what I want to do now is replace the found matches, or rather modify. I want to wrap the found matches with a span tag. So I used this code:
var spanOpen = '<span style="color: silver;">';
var spanClose = '</span>';
text.replace(re, spanOpen + text.match(re) + spanClose);
even though the code works, I don't get the result I want. It outputs:
as HTML
this <span style="color: silver;">(is),(ran)</span> some <span style="color: silver;">(is),(ran)</span>dom text
as text
this (is),(ran) some (is),(ran)dom text
You can check the example in fiddle. How can I fix this?
The code in fiddle:
var text = "this (is) some (ran)dom text";
var re = /(\(\w*\))/g;
var spanOpen = '<span style="color: silver;">';
var spanClose = '</span>';
var original = "original: " + text + "<br>";
var desired = "desired: this " +spanOpen+"(is)"+spanClose+ " some " +spanOpen+"(ran)"+spanClose+ "dom text<br>";
var output = "output: " + text.replace(re, spanOpen + text.match(re) + spanClose);
var result = original + desired + output;
document.body.innerHTML = result;
If the title is wrong or misleading, I'll change it.
The .replace() method can take a function as the 2nd parameter. That will come in handy here.
var output = "output: " + text.replace(re, function(match){
return spanOpen + match + spanClose
});
The function will be called for each individual match.
You can also use '$&' in your replace string to reference each match
var output = "output: " + text.replace(re, spanOpen + '$&' + spanClose);
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
text.match(re) is returning an array of the result, so what you can do is loop this array and replace your string with each items, like this:
var matches = text.match(re);
var output = "output: " + text;
for (var i = 0; i < matches.length; i++)
{
output = output.replace(matches[i], spanOpen + matches[i] + spanClose);
}
See this FIDDLE

How to wrap text in span tags except first word with jQuery?

Is it possible to wrap the last words in a string with span tags excluding the first word? So it'd be for example:
var string = 'My super text';
Becomes
My <span>super text</span>
I have this:
var text = string.split(" ");
// drop the last word and store it in a variable
var last = text.pop();
// join the text back and if it has more than 1 word add the span tag
// to the last word
if (text.length > 0) {
return text.join(" ") + " <span>" + last + "</span>";
}
else {
return "<span>" + text.join(" ") + last + "</span>";
}
Which wraps the last word with span tags if it has at least two but not sure how to modify it.
You just need to use text.shift() which will return the first word, instead of text.pop() which returns the last word. Then it will be much easier to accomplish this.
var text= string.split(" ");
// get the first word and store it in a variable
var first = text.shift();
// join the text back and if it has more than 1 word add the span tag
// to the last word
if (text.length > 0) {
return first + " <span>" + text.join(" ") + "</span>";
} else {
return "<span>" + first + "</span>";
}
You could do it with a regular expression.
text = text.replace(/\s(.*)$/, ' <span>$1</span>');
However, you should probably turn the following into a recursive function...
$('body').contents().filter(function() {
return this.nodeType == 3;
}).each(function() {
var node = this;
// Normalise node.
node.data = $.trim(node.data);
node.data.replace(/\s+(.*)\s*$/, function(all, match, offset) {
var chunk = node.splitText(offset);
chunk.parentNode.removeChild(chunk);
var span = document.createElement('span');
span.appendChild(document.createTextNode(' ' + match));
node.parentNode.appendChild(span);
});
});
jsFiddle.
This will allow you to modify text nodes and insert the span elements without messing with serialised HTML.
var space = string.indexOf(' ');
if (space !== -1) {
return string.slice(0,space) + " <span>" + string.slice( space ) + "</span>";
} else {
return "<span>" + string + "</span>";
}
You don't have to split the text, just check if there is a space, and insert a span there.
This code inserts a span after the first space, and if there is no space (idx == -1), the span is put at the beginning of the string:
var idx = string.indexOf(' ');
return string.substr(0, idx + 1) + "<span>" + string.substr(idx + 1) + "</span>";

Categories