Truncating or Summarizing Text with html part in HTML - javascript

Am loading some blog data from a database with title and body but the body contains some HTML and CSS codes like the following below in the JSON data
{[News_Body: "<span style=\"color: black;\">The Lagos State Local Government
Election Appeal Tribunal have received 22 Appeals from the July
22 council polls in Lagos State.<br />\n <br />\n The
Chairperson of the 2017 Local Government Election Appeal
Tribunal, Justice G. M Onyeabo, stated this today 25th of
October at the tribunal's inaugural sitting. <br />\n <br
/>\n The tribunal had earlier been inaugurated on the 23 of
October, 2017 pursuant to Section 7 of the Local Government
Election Tribunal Law 2008, will hear and determine the appeals
in 21 days.<br />\n <br />\n Justice Onyeabo and four other
justices: O. Kasali, A. Onigbanjo, O.A Dabiri and K. A Jose make
up the panel.<br />\n <br />"
News_Title: "PRESS RELEASE - LAGOS LG ELECTION APPEAL TRIBUNAL RECEIVES 22
APPEALS"
Posted_By: "Ololade Ige"
Posted_Date: "10/31/2017 12:00:00 AM"], ...}
The problem I have is taking the body and summarizing its contents. I tried the following but it did not work as expected.
using CSS
.truncate {
height: 200px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
Loading the data dynamically with javascript because it is coming from database
var p = document.createElement('p');
p.setAttribute('style', 'text-align:center; color: #ffffff !important;');
p.setAttribute('class', 'truncate');
var newSum = summary.split('<br />');;
p.innerHTML = newSum[0];
but the problem with the above is that not all object.News_Body contains a line break <br />. I don't have control as to how the data is stored, I just process what am given. Sadly :(

If jQuery is an option you could achieve something very quickly using the text function and some string manipulation.
var text = $("<div>" + content.News_Body + "</div>").text().substring(0, 3) + "..."
Just replace the 3 with your max content length. So substring(0, 10) will show 10 characters etc...
EDIT:
Using the link that #FMK posted at Strip HTML from Text JavaScript it would look like:
var text = strip("<div>" + content.News_Body + "</div>").substring(0, 3) + "..."
Which is a non-jquery option too.

I combined the two replies and I did this.
var p = document.createElement('p');
p.setAttribute('style', 'text-align:center; color: #ffffff !important;');
p.setAttribute('class', '');// removed my css truncate style class
var s = strip(summary).substring(0, 300) + "...";
p.innerHTML = s;
I got the strip function from Strip HTML from Text JavaScript
Thanks for the quick replies. You guys are awsome!!

Related

Save the textarea value and format [duplicate]

I am getting the value in a textarea when the user hits submit. I then take this value and place it elsewhere on the page. However, when I do this, it loses newline characters making the output pretty ugly.
Here is the textarea I am accessing:
<textarea id="post-text" class="form-control" rows="3" placeholder="What's up?" required></textarea>
Here is the JavaScript code accessing the post and transcribing it.
var post = document.createElement('p');
var postText = document.getElementById('post-text').value;
post.append(postText);
var card = document.createElement('div');
card.append(post);
var cardStack = document.getElementById('#card-stack');
cardStack.prepend(card);
When the input is something like:
Group Schedule:
Tuesday practice # 5th floor (8 pm - 11 pm)
Thursday practice # 5th floor (8 pm - 11 pm)
Sunday practice # (9 pm - 12 am)
The output is:
Group Schedule: Tuesday practice # 5th floor (8 pm - 11 pm) Thursday practice # 5th floor (8 pm - 11 pm) Sunday practice # (9 pm - 12 am)
So is there a way to preserve line breaks?
The easiest solution is to simply style the element you're inserting the text into with the following CSS property:
white-space: pre-wrap;
This property causes whitespace and newlines within the matching elements to be treated in the same way as inside a <textarea>. That is, consecutive whitespace is not collapsed, and lines are broken at explicit newlines (but are also wrapped automatically if they exceed the width of the element).
Given that several of the answers posted here so far have been vulnerable to HTML injection (e.g. because they assign unescaped user input to innerHTML) or otherwise buggy, let me give an example of how to do this safely and correctly, based on your original code:
document.getElementById('post-button').addEventListener('click', function () {
var post = document.createElement('p');
var postText = document.getElementById('post-text').value;
post.append(postText);
var card = document.createElement('div');
card.append(post);
var cardStack = document.getElementById('card-stack');
cardStack.prepend(card);
});
#card-stack p {
background: #ddd;
white-space: pre-wrap; /* <-- THIS PRESERVES THE LINE BREAKS */
}
textarea {
width: 100%;
}
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:
Tuesday practice # 5th floor (8pm - 11 pm)
Thursday practice # 5th floor (8pm - 11 pm)
Sunday practice # (9pm - 12 am)</textarea><br>
<input type="button" id="post-button" value="Post!">
<div id="card-stack"></div>
Note that, like your original code, the snippet above uses append() and prepend(). As of this writing, those functions are still considered experimental and not fully supported by all browsers. If you want to be safe and remain compatible with older browsers, you can substitute them pretty easily as follows:
element.append(otherElement) can be replaced with element.appendChild(otherElement);
element.prepend(otherElement) can be replaced with element.insertBefore(otherElement, element.firstChild);
element.append(stringOfText) can be replaced with element.appendChild(document.createTextNode(stringOfText));
element.prepend(stringOfText) can be replaced with element.insertBefore(document.createTextNode(stringOfText), element.firstChild);
as a special case, if element is empty, both element.append(stringOfText) and element.prepend(stringOfText) can simply be replaced with element.textContent = stringOfText.
Here's the same snippet as above, but without using append() or prepend():
document.getElementById('post-button').addEventListener('click', function () {
var post = document.createElement('p');
var postText = document.getElementById('post-text').value;
post.textContent = postText;
var card = document.createElement('div');
card.appendChild(post);
var cardStack = document.getElementById('card-stack');
cardStack.insertBefore(card, cardStack.firstChild);
});
#card-stack p {
background: #ddd;
white-space: pre-wrap; /* <-- THIS PRESERVES THE LINE BREAKS */
}
textarea {
width: 100%;
}
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:
Tuesday practice # 5th floor (8pm - 11 pm)
Thursday practice # 5th floor (8pm - 11 pm)
Sunday practice # (9pm - 12 am)</textarea><br>
<input type="button" id="post-button" value="Post!">
<div id="card-stack"></div>
Ps. If you really want to do this without using the CSS white-space property, an alternative solution would be to explicitly replace any newline characters in the text with <br> HTML tags. The tricky part is that, to avoid introducing subtle bugs and potential security holes, you have to first escape any HTML metacharacters (at a minimum, & and <) in the text before you do this replacement.
Probably the simplest and safest way to do that is to let the browser handle the HTML-escaping for you, like this:
var post = document.createElement('p');
post.textContent = postText;
post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n');
document.getElementById('post-button').addEventListener('click', function () {
var post = document.createElement('p');
var postText = document.getElementById('post-text').value;
post.textContent = postText;
post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n'); // <-- THIS FIXES THE LINE BREAKS
var card = document.createElement('div');
card.appendChild(post);
var cardStack = document.getElementById('card-stack');
cardStack.insertBefore(card, cardStack.firstChild);
});
#card-stack p {
background: #ddd;
}
textarea {
width: 100%;
}
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:
Tuesday practice # 5th floor (8pm - 11 pm)
Thursday practice # 5th floor (8pm - 11 pm)
Sunday practice # (9pm - 12 am)</textarea><br>
<input type="button" id="post-button" value="Post!">
<div id="card-stack"></div>
Note that, while this will fix the line breaks, it won't prevent consecutive whitespace from being collapsed by the HTML renderer. It's possible to (sort of) emulate that by replacing some of the whitespace in the text with non-breaking spaces, but honestly, that's getting rather complicated for something that can be trivially solved with a single line of CSS.
The target container should have the white-space:pre style.
Try it below.
<script>
function copycontent(){
var content = document.getElementById('ta').value;
document.getElementById('target').innerText = content;
}
</script>
<textarea id='ta' rows='3'>
line 1
line 2
line 3
</textarea>
<button id='btn' onclick='copycontent();'>
Copy
</button>
<p id='target' style='white-space:pre'>
</p>
function get() {
var arrayOfRows = document.getElementById("ta").value.split("\n");
var docfrag = document.createDocumentFragment();
var p = document.getElementById("result");
while (p.firstChild) {
p.removeChild(p.firstChild);
}
arrayOfRows.forEach(function(row, index, array) {
var span = document.createElement("span");
span.textContent = row;
docfrag.appendChild(span);
if(index < array.length - 1) {
docfrag.appendChild(document.createElement("br"));
}
});
p.appendChild(docfrag);
}
<textarea id="ta" rows=3></textarea><br>
<button onclick="get()">get</button>
<p id="result"></p>
You can split textarea rows into array:
var arrayOfRows = postText.value.split("\n");
Then use it to generate, maybe, more p tags...
Here is an idea as you may have multiple newline in a textbox:
var text=document.getElementById('post-text').value.split('\n');
var html = text.join('<br />');
This HTML value will preserve newline. Hope this helps.
You could set width of div using Javascript and add white-space:pre-wrap to p tag, this break your textarea content at end of each line.
document.querySelector("button").onclick = function gt(){
var card = document.createElement('div');
card.style.width = "160px";
card.style.background = "#eee";
var post = document.createElement('p');
var postText = document.getElementById('post-text').value;
post.style.whiteSpace = "pre-wrap";
card.append(post);
post.append(postText);
document.body.append(card);
}
<textarea id="post-text" class="form-control" rows="3" placeholder="What's up?" required>
Group Schedule:
Tuesday practice # 5th floor (8pm - 11 pm)
Thursday practice # 5th floor (8pm - 11 pm)
Sunday practice # (9pm - 12 am)</textarea>
<br><br>
<button>Copy!!</button>
I suppose you don't want your textarea-content to be parsed as HTML. In this case, you can just set it as plaintext so the browser doesn't treat it as HTML and doesn't remove newlines No CSS or preprocessing required.
<script>
function copycontent(){
var content = document.getElementById('ta').value;
document.getElementById('target').innerText = content;
}
</script>
<textarea id='ta' rows='3'>
line 1
line 2
line 3
</textarea>
<button id='btn' onclick='copycontent();'>
Copy
</button>
<p id='target'></p>
Similar questions are here
detect line breaks in a text area input
detect line break in textarea
You can try this:
var submit = document.getElementById('submit');
submit.addEventListener('click', function(){
var textContent = document.querySelector('textarea').value;
document.getElementById('output').innerHTML = textContent.replace(/\n/g, '<br/>');
});
<textarea cols=30 rows=10 >This is some text
this is another text
Another text again and again</textarea>
<input type='submit' id='submit'>
<p id='output'></p>
document.querySelector('textarea').value; will get the text content of the
textarea and textContent.replace(/\n/g, '<br/>') will find all the newline character in the source code /\n/g in the content and replace it with the html line-break <br/>.
Another option is to use the html <pre> tag. See the demo below
var submit = document.getElementById('submit');
submit.addEventListener('click', function(){
var content = '<pre>';
var textContent = document.querySelector('textarea').value;
content += textContent;
content += '</pre>';
document.getElementById('output').innerHTML = content;
});
<textarea cols=30 rows=10>This is some text
this is another text
Another text again and again </textarea>
<input type='submit' id='submit'>
<div id='output'> </div>

Parse RSS <content:encoded> with native javaScript

I'm parsing a RSS feed which looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:npr="http://www.npr.org/rss/" xmlns:nprml="http://api.npr.org/nprml" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:content="http://purl.org/rss/1.0/modules/content/" version="2.0">
<channel>
<title>News</title>
<link>http://www.npr.org/templates/story/story.php?storyId=1001&ft=1&f=1001</link>
<description>NPR news, audio, and podcasts. Coverage of breaking stories, national and world news, politics, business, science, technology, and extended coverage of major national and world events.</description>
<language>en</language>
<copyright>Copyright 2012 NPR - For Personal Use Only</copyright>
<generator>NPR API RSS Generator 0.94</generator>
<lastBuildDate>Tue, 28 Aug 2012 12:19:00 -0400</lastBuildDate>
<image>
<url>http://media.npr.org/images/npr_news_123x20.gif</url>
<title>News</title>
<link>http://www.npr.org/templates/story/story.php?storyId=1001&ft=1&f=1001</link>
</image>
<item>
<title>Reports: Obama Administration Will Unveil New Fuel-Efficiency Standards</title>
<description>The new rules will require U.S. cars to average 54.5 miles per gallon by 2025.</description>
<pubDate>Tue, 28 Aug 2012 12:19:00 -0400</pubDate>
<link>http://www.npr.org/blogs/thetwo-way/2012/08/28/160172356/reports-obama-administration-will-unveil-new-fuel-efficiency-standards?ft=1&f=1001</link>
<guid>http://www.npr.org/blogs/thetwo-way/2012/08/28/160172356/reports-obama-administration-will-unveil-new-fuel-efficiency-standards?ft=1&f=1001</guid>
<content:encoded><![CDATA[<p>The new rules will require U.S. cars to average 54.5 miles per gallon by 2025.</p><p>» E-Mail This » Add to Del.icio.us</p>]]></content:encoded>
</item>
</channel>
</rss>
I'm looping the items like this:
var channel = xml.documentElement.getElementsByTagName("channel");
var items = xml.documentElement.getElementsByTagName("item");
for (var i = 0; i < items.length; i++) {
var ul = document.getElementById("feed");
var li = document.createElement('li');
var item = items.item(i);
var title = item.getElementsByTagName("title").item(0).textContent;
var link = item.getElementsByTagName("link").item(0).textContent;
var description = item.getElementsByTagName("link").item(0).textContent;
//var content = item.getElementsByTagName('content\\:encoded').item(0).textContent;
var li = document.createElement('li');
li.innerHTML = '' + title + '';
document.getElementById('feed').appendChild(li);
}
But how can I get the contents of the node <content:encoded>?
I tried with: item.getElementsByTagName('content\\:encoded').item(0).textContent; but it's not working.
Using jQuery this one inside .each() works: $(this).find('content\\:encoded').text(); but I'd rather use native javaScript.
So, it seems that I needed to use the tag getElementsByTagNameNS and that the node was "encoded" - like this:
var content = item.getElementsByTagNameNS("*", "encoded").item(0).textContent;
my solution:
var result2 = JSON.parse(result1);
setData(result2.rss.channel.item[0].["content:encoded"]);
jus use ["content:encoded"]

Javascript: My .textContent works, but not my innerHTML

I have a strange problem. In general, when I set a variable as textContent, it shows it, but it doesn't when I set it as innerHTML
More precisely
Here is the HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Dynamic Menu</title>
</head>
<body id="top">
<h1>The Extremadura Region of Western Spain</h1>
<h2 >Geography Of The Region</h2>
<p>The autonomous community of Extremadura is in western Spain alongside the Portuguese border.
It borders the Spanish regions of Castilla y Leon, Castilla La Mancha and Andalucía as well as Portugal (to the West).
Covering over 40,000 square kilometers it has two provinces: Cáceres in the North and Badajoz in the South.</p>
<h2>Where To Stay</h2>
<p>There is a wide range of accommodation throughout Extremadura including small inns and guest houses ('Hostals') or
think about renting a 'casa rural' (country house) if you are travelling in a group.</p>
<h2>Climate</h2>
<p>Generally Mediterranean, except for the north, where it is continental. Generally known for its extremes,
including very hot and dry summers with frequent droughts, and its long and mild winters.</p>
<h2>What To See</h2>
<p>Extremadura hosts major events all year round including theater, music, cinema, literature and folklore.
Spectacular venues include castles, medieval town squares and historic centers.
There are special summer theater festivals in the Mérida, Cáceres, Alcántara and Alburquerque.</p>
<h2>Gastronomy</h2>
<p>The quality of Extremaduran food arises from the fine quality of the local ingredients.
In addition to free-range lamb and beef, fabulous cheeses, red and white wines, olive oil, honey and paprika,
Extremadura is particularly renowned for Iberian ham. The 'pata negra' (blackfoot) pigs are fed on acorns in the
cork-oak forests, the key to producing the world's best ham and cured sausages.</p>
<script src="lunch.js"></script>
</body>
</html>
Here is the script
function lop(){
var hs = document.getElementsByTagName('h2');
for(var g = 0; g<hs.length; g++){
hs[g].setAttribute('id', g);
}
var budy = document.getElementById('top'); //Gets the body id
var nnn = document.createElement('nav'); //Creats a nav event
var uuu = "<ul > \
<li id='one'> <a href='#0'>Geography Of The Region </a> </li> \
<li id='two'> <a href='#1'>Where To Stay </a> </li> \
<li id='tre'> <a href='#2'>Climate </a> </li> \
<li id='for'> <a href='#3'>What To See</a> </li> \
<li id='fiv'> <a href='#4'>Gastronomy</a> </li>";
// li: 55-60 make the HTML
nnn.innerHTML = uuu; //Sets the HTML to the nav
var h = document.getElementsByTagName('h2')[0]; // Get the specific element
budy.insertBefore(nnn, h); // inserts the element nav and the whole html before h
var ps = document.getElementsByTagName('p');
var hih = ' AAAAA ';
for(var g = 0; g<ps.length; g++){
ps[g].nextSibling.innerText = hih;
}
}
lop(); //cals the function so it executes
So basicly in this exercise i have to create an ul within the script and without modyfing the HTML.
I successed in creating an ul. Then I have to creat a link that brings me to the top of the page. Which is this part here:
var ps = document.getElementsByTagName('p');
var hih = ' AAAAA ';
for(var g = 0; g<ps.length; g++){
ps[g].nextSibling.innerText = hih;
}
Here I try to creat a link that bring me back to the top. Im using the advantage that chrome has blank space betwwen sibling to creat that link in there.
The problem is that it doesn't show. When I go to my debugger, I have no errors, but nothings shows. If change ps[g].nextSibling.innerText = hih; for .textContent it shows the whole think.
I know the difference between .innerHTML and .textContent (or I think), so why doesn't it show my link and can I make it show ?
I don't understand you use nextSibling. If you want to use innerHTML, you can use bellow script
ps[g].innerHTML = ps[g].innerHTML + hih;
You can read about nextSibling in https://www.w3schools.com/jsref/prop_node_nextsibling.asp
Ok so a friend of mine changed my procedure and here what he did:
var ps = document.getElementsByTagName('p');
var hih = '<br /><br /> To the top ';
for(var g = 0; g<ps.length; g++) {
ps[g].innerHTML += hih;
}
In other words, what I learned from this 3h of js, is that you can't change a blank child's HTML, but only his text.

Parse RSS feed with multiple <link> (jquery)

I'm using jQuery to parse and output three RSS feeds into three different container divs. The first two feeds work fine, but I can't get the links to work in the third feed, the href isn't found at all. See fiddle http://jsfiddle.net/a68myvm2/1/
I'm thinking that it has to do with that the third feed contains multiple link tags per item. I've tried searching the web for a solution without success.
HTML
<div id="content_1"></div>
<div id="content_2"></div>
<div id="content_3"></div>
JS
$(function () {
function GetFeeds(){
var urls = ['http://www.gosugamers.net/counterstrike/news/rss', 'http://www.hltv.org/news.rss.php', 'http://feeds.thescoreesports.com/csgo.rss'];
urls.forEach(function(Query){
$.ajax({
type: "GET",
url: 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q='+encodeURIComponent(Query),
dataType: 'json',
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function(xml) {
var Content=parseInt(urls.indexOf(Query))+1;
$("#content_"+Content).html('');
$.each(xml.responseData.feed.entries, function(idx, value){
$("#content_"+Content).append('<a class="news-item" href="' + value.link + '" title="' + value.title +'" target="_blank"><p>' + value.publishedDate + '</p><h3>' + value.title + '</h3></a><hr>');
});
}
});
});
}
//Call GetFeeds every 5 seconds.
setInterval(GetFeeds,5000);
//Page is ready, get feeds.
GetFeeds();
});
Part of problematic feed (http://feeds.thescoreesports.com/csgo.rss)
<item>
<guid isPermaLink="false">4117</guid>
<title>ScrunK joins Team Coast as Coach</title>
<link>http://www.thescoreesports.com/news/4117</link>
<pubDate>Wed, 30 Sep 2015 18:02:45 +0000</pubDate>
<dc:creator/>
<media:content url="https://dqrt72khb0whk.cloudfront.net/uploads/image/file/2729/w1080xh810_coast.jpg?ts=1432916713">
<media:credit>Team Coast</media:credit>
</media:content>
<content:encoded>
<![CDATA[<p>Team Coast have brought in German CS:GO professional, Robin "<strong>ScrunK</strong>" Röpke, to take the reigns as the team's coach, the organization announced Wednesday. </p><figure><blockquote class="twitter-tweet" lang="en"><p lang="en" dir="ltr">We would like to officially welcome #CSTScrunK as our new CS:GO coach! Please show your support and give him a follow!!</p>— Team Coast (#TeamCoastGaming) September 30, 2015</blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></figure><p>"I would like to thank Team Coast and the players for giving me this opportunity to throw my EU knowledge and style into the NA scene," said ScrunK in his statement to HLTV.org. "I am excited to see where this route in my career leads me and where I can help this team go."</p><p>Team Coast are currently competing in the North American divisions of both CEVO-P Season 8 and ESL ESEA Pro League Season 2. They currently sit at sixth in the CEVO-P division with a 2-4-3 record and third in the ESL ESEA Pro League with a record of 3-4.</p><p><em>Paul Park is a wr​iter for theScore eSports. <a target="_blank" href="https://twitter.com/phjpark">You can follow him on Twitter</a>.</em></p><p><small><em>Copyright © 2015 Score Media Ventures Inc. All rights reserved. Certain content reproduced under license.</em></small></p>]]>
</content:encoded>
<link rel="related" type="text/html" href="http://www.thescoreesports.com/news/4070" title="Dead Pixels CS:GO part ways with FARIS and YOUNS"/>
<link rel="related" type="text/html" href="http://www.thescoreesports.com/news/4115" title="G2.Kinguin add jkaem to roster"/>
<link rel="related" type="text/html" href="http://www.thescoreesports.com/news/4102" title="ESL ESEA Pro League Hot Match of week 3"/>
<link rel="related" type="text/html" href="http://www.thescoreesports.com/news/4061" title="HIGHLIGHT: azr shuts down Winterfox"/>
<link rel="related" type="text/html" href="http://www.thescoreesports.com/news/4063" title="DreamHack Stockholm Group B Roundup: Down and out"/>
</item>

Add span class a specific word with regexp

<div id="mytext">
"Albert" Einstein German: 14 March 1879 – 18 April 1955 was a German-born theoretical physicist.
He developed the general theory of "relativity", one of the two pillars of modern physics (alongside quantum mechanics).
He is best known in popular culture for "his" mass–energy equivalence formula "E = mc2" (which has been dubbed "the world's most famous equation").
</div>
i want in " " words add span class with javascript regexp
<div id="mytext">
<span class="myclass">"Albert"</span> Einstein German: 14 March 1879 – 18 April 1955 was a German-born theoretical physicist.
He developed the general theory of <span class="myclass">"relativity"</span>, one of the two pillars of modern physics (alongside quantum mechanics).
He is best known in popular culture for <span class="myclass">"his"</span> mass–energy equivalence formula <span class="myclass">"E = mc2"</span (which has been dubbed the world's most famous equation).
</div>
Here's a plain vanilla JS way and a jQuery way:
jQuery
$("#mytext").html( $("#mytext").text().replace(/("[^"]*")/g,"<span>$1</span>") )
JavaScript
var text = document.getElementById('mytext').innerHTML;
document.getElementById('mytext').innerHTML = text.replace(/("[^"]*")/g,"<span>$1</span>")
Was answered a few times.
http://jsfiddle.net/59Nrk/
Exmaple:
$.fn.highlight = function (str, className) {
var regex = new RegExp("\\b"+str+"\\b", "gi");
return this.each(function () {
this.innerHTML = this.innerHTML.replace(regex, function(matched) {return "<span class=\"" + className + "\">" + matched + "</span>";});
});
};
// Shorthand for $( document ).ready()
$(function() {
var $txtBlock = $('#mytext'),
highlightClass = 'myclass';
$txtBlock.highlight('Einstein', highlightClass);
$txtBlock.highlight('relativity', highlightClass);
$txtBlock.highlight('his', highlightClass);
});
Highlight a word with jQuery

Categories