Find alphanumeric characters, text and replace with HTML - javascript

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");
}

Related

Javascript replace() using html entities not working

I've got the following script, which successfully replaces < and > with the code indicated below. The idea here is that a user would put into the text box if they want "Bold me" to appear bolded on their blog.
$('.blogbody').each(function() {
var string = $(this).html();
$(this).html(string.replace('<', '<span class="bold">'));
});
$('.blogbody').each(function() {
var string = $(this).html();
$(this).html(string.replace('>', '</span>'));
});
The problem comes with other html entities. I'm going to simply my example. I want to replace the [ html entity with a paragraph tag, but none of the lines in this script work. I've tried documenting each code that related to the '[' character.
$('.blogbody').each(function() {
var string = $(this).html();
$(this).html(string.replace('[', '<p>'));
});
$('.blogbody').each(function() {
var string = $(this).html();
$(this).html(string.replace('&lbrack;', '<p>'));
});
$('.blogbody').each(function() {
var string = $(this).html();
$(this).html(string.replace('&lsqb;', '<p>'));
});
$('.blogbody').each(function() {
var string = $(this).html();
$(this).html(string.replace('&lbrack;', '<p>'));
});
Any thoughts on this would be greatly appreciated! Thanks!
The character '[' is not a character entity so it is not encoded. Just pass it directly to replace:
string.replace('[' , '<p>')

a matching word function with 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 );
});

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

Replacing an emoticon in a string unless within a certain group of text

I'm trying to replace emoticons in a given string with an image tag only if it is not within a certain group of characters.
Given:
var reg = /(?!<):\/(?![^<>]*>)/g,
string = ':/ http://blah.com :/',
result = string.replace(reg, 'IMG');
Result: IMG httpIMG/blah.com IMG
I want to know if there is a way to ignore the replacement within the HTML tags instead of just within the <>.
Maybe this is not the best solution but if you use jQuery the following "oneliner" can do the job:
var str = ":/ <a href='http://blah.com'>http://blah.com</a> :/";
$("<div />", { html : str }).contents().each(function() {
if (this.nodeType === 3)
this.nodeValue = this.nodeValue.replace(/:\//g, "IMG");
}).end().html();
DEMO: http://jsfiddle.net/Hfnje/
why not match it against word boundaries?
/\B:\/\B/
which would match:
:/
foo :/ bar
but not:
http://
foo:/bar
With help from #VisioN, I managed to come up with this:
message =
$('<div />', html: message).contents().each(->
if #nodeType is 3
for replacement, emoticons of self.emoticons
for emoticon in emoticons
#nodeValue = #nodeValue.replace new RegExp(emoticon, 'g'),
$('<span />', class:'emoticon ' + replacement, title: emoticon)[0].outerHTML
$(#).replaceWith #nodeValue
).end().html()
It's not pretty, but it's working.

Replacing tab characters in JavaScript

Please consider the following HTML <pre> element:
This is some
example code which
contains tabs
I would like to replace all of the tab characters with four non-breaking space characters in HTML (i.e. ). I have tested the above pre element with JavaScript for the presence of tab characters as follows:
$('pre').ready(function() {
alert(/\t/.test($(this).text()));
});
But it is always returned false. Can anyone tell me the correct process by which to replace tab spaces from the source code to HTML NBSPs? The tabs have been added by Komodo Edit, and are visible when viewing the source.
You can do it like this:
$('pre').html(function() {
return this.innerHTML.replace(/\t/g, ' ');
});
That will loop through all pre elements on the page and call the function for each of them. jQuery's html function uses the return value of the function we give to replace the content of each element. We're using String#replace to replace all (note the g flag on the regexp) tab characters in the HTML string with four non-breaking spaces.
Live example
It removes line breaks, extra spaces and line breaks:
function removeNewlines(str) {
//remove line breaks from str
str = str.replace(/\s{2,}/g, ' ');
str = str.replace(/\t/g, ' ');
str = str.toString().trim().replace(/(\r\n|\n|\r)/g,"");
console.log(str);
}
Demo:
function removeNewlines(str) {
//remove line breaks from str
str = str.replace(/\s{2,}/g, ' ');
str = str.replace(/\t/g, ' ');
str = str.toString().trim().replace(/(\r\n|\n|\r)/g,"");
console.log(str);
}
$('#acceptString').click(function() {
var str = prompt('enter string','');
if(str)
removeNewlines(str)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' value='Enter String' id='acceptString' />
Try this:
var tab = RegExp("\\t", "g");
document.getElementById("text").value =
document.getElementById("text").value.replace(tab,' ');

Categories