a matching word function with javascript - javascript

I am trying to write some code that will match words typed into a text input with words in div's with the class 'searchable' and highlights these words. What I have now works if one or more word matches and there are no words which don't match. For example, if the searchable div had the phrase: hello world and in the input was hello world it would highlight both. If the input had just hello, it would highlight that word. But if the input had hello mars, it would not highlight the word hello, because mars is not in the string. this jsFiddle demonstrates this. Any ideas much appreciated. Here is the code. Thank you.
javaScript:
if($('#search').val().length !== 0){
$('.searchable').each(function(){
var search_value = $("#search").val();
var search_regexp = new RegExp(search_value, "g");
$(this).html($(this).html().replace(search_regexp,"<span class ='highlight'>"+search_value+"</span>"));
});
}
html:
<input type = "text" id = "search" value = "hello mars">
<div class = "searchable">hello world</div>

Something like this:
// http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
String.prototype.pregQuote = function()
{
return this.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};
var keyword = $("#search").val();
var searchRegex = new RegExp( '(' + keyword.pregQuote() + ')' , "ig" );
$('.searchable').each(function(){
var html = $(this).html();
html = html.replace( searchRegex , '<span class="highlight">$1</span>');
$(this).html( html );
});

Related

Replace HTML Comment along with string variable

In my project I have some html with comments surrounding text so I can find the text between particular comments and replace that text whilst leaving the comments so I can do it again.
I am having trouble getting the regex to work.
Here is an html line I am working on:
<td class="spaced" style="font-family: Garamond,Palatino,sans-serif;font-size: medium;padding-top: 10px;"><!--firstname-->Harrison<!--firstname--> <!--lastname-->Ford<!--lastname--> <span class="spacer"></span></td>
Now, here is the javascript/jquery that I have at the moment:
var thisval = $(this).val(); //gets replacement text from a text box
var thistoken = "firstname";
currentTemplate = $("#gentextCodeArea").text(); //fetch the text
var tokenstring = "<!--" + thistoken + "-->"
var pattern = new RegExp(tokenstring + '\\w+' + tokenstring,'i');
currentTemplate.replace(pattern, tokenstring + thisval + tokenstring);
$("#gentextCodeArea").text(currentTemplate); //put the new text back
I think I'm pretty close, but I don't have the regex right yet.
The regex ought to replace the firstname with whatever is entered in the textbox for $thisval (method is attached to keyup procedure on textbox).
Using plain span tags instead of comments would make things easier, but either way, I would suggest not using regular expressions for this. There can be border cases that may lead to undesired results.
If you stick with comment tags, I would iterate over the child nodes and then make the replacement, like so:
$("#fname").on("input", function () {
var thisval = $(this).val(); //gets replacement text from a text box
var thistoken = "firstname";
var between = false;
$("#gentextCodeArea").contents().each(function () {
if (this.nodeType === 8 && this.nodeValue.trim() === thistoken) {
if (between) return false;
between = true;
} else if (between) {
this.nodeValue = thisval;
thisval = '';
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
New first name: <input id="fname">
<div id="gentextCodeArea">
<!--firstname-->Harrison<!--firstname-->
<!--lastname-->Ford<!--lastname-->
<span class="spacer"></span></div>
What went wrong in your code
By using text() you don't get the comment tags. To get those, you need to use html() instead
replace() does not mutate the variable given in the first argument, but returns the modified string. So you need to assign that back to currentTemplate
It would be better to use [^<]* instead of \w+ for matching the first name, as some first names have non-letters in them (hyphen, space, ...), and it may even be empty.
Here is the corrected version, but I insist that regular expressions are not the best solution for such a task:
$("#fname").on("input", function () {
var thisval = $(this).val(); //gets replacement text from a text box
var thistoken = "firstname";
currentTemplate = $("#gentextCodeArea").html(); //fetch the html
var tokenstring = "<!--" + thistoken + "-->"
var pattern = new RegExp(tokenstring + '[^<]*' + tokenstring,'i');
currentTemplate = currentTemplate.replace(pattern, tokenstring + thisval + tokenstring);
$("#gentextCodeArea").html(currentTemplate); //put the new text back
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
New first name: <input id="fname">
<div id="gentextCodeArea">
<!--firstname-->Harrison<!--firstname-->
<!--lastname-->Ford<!--lastname-->
<span class="spacer"></span></div>
here is a function which will generate an appropriate Regular expression:
function templatePattern(key) {
return new RegExp(`<!--${key}-->(.*?)<!--${key}-->`);
}
the (.*?) means "match as little as possible," so it will stop at the first instance of the closing tag.
Example:
'<!--firstname-->Harrison<!--firstname--> <!--lastname-->Ford<!--lastname-->'
.replace(templatePattern('firstname'), 'Bob')
.replace(templatePattern('lastname'), 'Johnson') // "Bob Johnson"
$(function(){
function onKeyUp(event)
{
if(event.which === 38) // if key press was the up key
{
$('.firstname_placeholder').text($(this).val());
}
}
$('#firstname_input').keyup(onKeyUp);
});
input[type=text]{width:200px}
<input id='firstname_input' type='text' placeholder='type in a name then press the up key'/>
<table>
<tr>
<td ><span class='firstname_placeholder'>Harrison</span> <span class='lastname_placeholder'>Ford</span> <span class="spacer"></span></td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Find alphanumeric characters, text and replace with HTML

I'm trying to find and replace text in an HTML. And adding a bold element around the text.
For example, lets say I have the following text:
<div>This is a test content and I'm trying to write testimonial of an user.</div>
If user searches for "test" in my HTML string, I need to show all text containing search text in bold.
<div>This is a <b>test</b> content and I'm trying to write <b>test</b>imonial of an user.</div>
This is working using the below code:
$.fn.wrapInTag = function(opts) {
var o = $.extend({
words: [],
tag: '<strong>'
}, opts);
return this.each(function() {
var html = $(this).html();
for (var i = 0, len = o.words.length; i < len; i++) {
var re = new RegExp(o.words[i], "gi");
html = html.replace(re, o.tag + '$&' + o.tag.replace('<', '</'));
}
$(this).html(html);
});
$('div').wrapInTag({
tag: 'b',
words: ['test']
});
But the above javascript approach fails if I search something like:
*test or /test
Regex doesn't support here.
There are multiple approaches over net but none of them worked for alphanumeric text.
This is how I would perform the text highlight:
$("#search").keyup(function(){
$("#text").html($("#text").html().replace("<b>", "").replace("</b>", ""));
var reg = new RegExp($(this).val().replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"),"g");
$("#text").html($("#text").text().replace(reg, "<b>"+$("#search").val()+"</b>"));
});
Here is the JSFiddle demo
You need to escape the RegExp input. See How to escape regular expression in javascript?
function escapeRegExp(string){
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

How to strip specific tag into div in Javascript?

I have this html code
<div class="myDiv">
My link
<p>This is a paragraph</p>
<script>//This is a script</script>
</div>
And I this javascript:
$('.myDiv').children().each(
function() {
var strToStrip = $('.myDiv').html();
if ( this.tagName != 'A' ) {
// Strip tag element if tagName is not 'A'
// and replace < or > with < or >
strToStrip.replace(/(<([^>]+)>)(?!(a))/ig, "");
}
}
);
How can I strip all tags, except from the a element?
I only need the link and strip tags if it is not a link tag.
I can't find what wrong with this code and what regex can I use to do this.
Any help please?
Try this regex example:
var strToStrip = $('.myDiv').html();
var temp = strToStrip.replace(/<[^a\/][a-z]*>/g, "<");
var result = temp.replace(/<\/[^a][a-z]*>/g, ">");
alert(result);
My goal of this question is to figure out how twitter do his hashtag or usergroup by using # or #. Go here to see the final result
you can use replace method of string using regular expr
var html = $("#main").html();
var result = html.replace(/[\<\>\/]/g,'');
alert(result);
the example shown here

Highlight given strings on a static HTML page with javascript

There is a static HTML file:
<html>
<body>
ABC
XYZ
foo
bar
</body>
</html>
Our question: How can I put in buttons/links (?) to this single, static HTML file, so that the people that are visiting this page can highlight given predetermined strings after clicking on the button/link on the page? With javascript? But how?
UPDATE: Place "ABC" from the above HTML into <big><b> tags like:
<big><b>ABC</b></big>
There are several ways you could do this.
a. Using plain javascript, you can try this:
1- Have a variable with the strings you want highlighted.
highlight = ['ABC', 'XYZ', ... ];
2- Make the function that highlights the strings from the highlight variable
makeHL = function(strings) {
// Get the HTML you want to search and replace strings on
myHTML = document.getElementsByTagName('body')[0].innerHTML;
// Use string.replace to add <b></b> to them or another form of highlighting.
// You can use regular expressions here to make it more reliable.
strings.forEach(function(str) {
myHTML = myHTML.replace(str, '<b>' + str + '</b>');
});
// Reinsert your new html with the strings highlighted.
document.getElementsByTagName('body')[0].innerHTML = myHTML
}
3- When the user clicks your link or your button, just call makeHL(highlights)
jsFiddle Here
Make sure that you include a Ecmascript5 shim such as es5-shim for use of .forEach() in browsers that don't support it.
b. Using a library like jQuery, it's easier to work around browser incompatibilities:
1- Include jQuery before the rest of the code:
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
2- Have a variable with your replacements:
highlight = ['ABC', 'XYZ', ... ];
3- Make the function that highlights the strings from the highlight variable and bind it to the click event:
$('.makeHL').on('click', function() {
// Get the HTML you want to search and replace strings on
myHTML = $('body').html();
// Use string.replace to add <b></b> to them or another form of highlighting.
// You can use regular expressions here to make it more reliable.
$.each(highlight, function(i, str) {
myHTML = myHTML.replace(str, '<b>' + str + '</b>');
});
// Reinsert your new html with the strings highlighted.
$('body').html(myHTML);
});
jsFiddle Here
Working example
HTML:
<p>
<button class="highlight-text">Highlight "ABC"</button>
</p>
ABC
XYZ
foo
bar
JS:
(function(){
function highlightText(textToHighlight) {
var searchExpression;
searchExpression = new RegExp('(' + textToHighlight + ')', 'g');
document.body.innerHTML = document.body.innerHTML.replace( searchExpression, '<b>$1</b>' );
}
document.querySelector('.highlight-text').addEventListener(
'click',
function(){ highlightText('ABC'); },
false
);
})();
http://jsfiddle.net/medda86/9g8XD/
html
ABC
XYZ
foo
bar
<button class="button">Button</button>
Jquery
var predefinedStrings = new Array('ABC','bar');
var arrLength = predefinedStrings.length;
$('.button').click(function(){
for (var i = 0;i < arrLength;i++){
$('body').html($('body').html().replace(predefinedStrings[i],'<b>'+predefinedStrings[i]+'</b>'));
}
});
I would suggest using Jquery javascript library
JQUERY
function highlight(word,content){
//gi makes the replace recursive and case insensitive
var regex = new RegExp( '(' +word+ ')', 'gi' );
return content.replace( regex, bold );
}
function unhighlight(word,content){
var regex = new RegExp( '(' +bold(word)+ ')', 'gi' );
return content.replace( regex, strip );
}
function bold(word){
return "<b>"+word+"</b>";
}
function strip(word){
return word.replace("<b>","").replace("</b>","");
}
highlighted = null;
$(document).ready(function (){
$("body").delegate(".highlight","click",function (e){
var word = $(this).text();
var container = $("body");
var content = container.html();
if(highlighted!=word){
//this is optional if you would like to unhighlight prev selections
content = unhighlight(highlighted,content);
content = highlight(word,content);
highlighted = word;
container.html(content);
}
});
});
HTML
<html>
<body>
ABC
XYZ
foo
bar
ABC
XYZ foo FOO Bar ABC
<button class="highlight">ABC</button>
<button class="highlight">FOO</button>
</body>
</html>
Heres a FIDDLE

Skill the tag between <> using regex in JS/jquery

Hello All Developers,
i need your help in one case so what my requirement is-
i am trying to find a String word in inner html using js like-
var index = lcBodyinnerhtml.indexOf(Searchword, 0);
so my problem is that if i am try to find a word suppose "all man " and in inner html it is
like
here in this world <i>all</i>man are
so it is not finding that word so i want that using regex or something it will skip the <> of html tag so that i 'll be able to find the exact word
Please suggest me any suitable example,thanks in advanced
You could do something like this
Html:
<div id="text">here in this world <i>all</i> man are all man</div>
Jquery / Javascript:
$(document).ready(function(){
var searchword = 'all man';
var text = $('#text').text();
var repl = '<span style="color:red">' + searchword + '</span>';
var rgxp = new RegExp(searchword, 'g');
text = text.replace(rgxp, repl);
$('#text').html(text);
});
Hope this helps!
1 minute of googling and I found this: http://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/
var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");
You can use the StrippedString to search for your Substring:
var OriginalString = "here in this world <i>all</i>man are"
var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");
// StrippedString = "here in this world allman are"

Categories