Highlight given strings on a static HTML page with javascript - 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

Related

Regex to remove dash and everything after it

I've got a function to remove the dash and everything that comes after it from a title.
This is the JS
<script>
(function() {
var str2 = document.querySelector('.dash-remove').innerHTML;
var txt2 = str2.replace(/ -.*$/g,"");
document.querySelector('.dash-remove').innerHTML = txt2;
})();
</script>
The Html is something like this
<h2 class="dash-remove">Testing - this function</h2>
However this isn't working, it's not removing the dash or the text after.
I've tried just removing the dash like this:
<script>
(function() {
var str2 = document.querySelector('.dash-remove').innerHTML;
var txt2 = str2.replace('-',"");
document.querySelector('.dash-remove').innerHTML = txt2;
})();
</script>
And this works so I assume it's something to do with the regex? any ideas?
As discussed in OP's comments, this may be due to the class being present multiple times. You should then use document.querySelectorAll along with NodeList#forEach :
(function() {
document.querySelectorAll('.dash-remove').forEach(item => {
item.innerHTML = item.innerHTML.replace(/ -.*$/g, '');
});
})();
The Html is something like this
<h2 class="dash-remove">Testing - this function</h2>
<h2 class="dash-remove">Testing - that function</h2>

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

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