Add span class a specific word with regexp - javascript

<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

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>

Highlighting text content using the content from an another div

I want to highlight the text content in paragraph using text content from an another div. So there is the "increase overall code" in the the first div. I want that these words from the main paragraph to be highlighted by using the first div. Thank you for the possibility to ask for help here!
function highlight() {
var htext = document.getElementById("torles");
var inputText = document.getElementById("inputText");
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text);
if (index >= 0) {
innerHTML = innerHTML.substring(0, index) + "<span class='highlight'>" + innerHTML.substring(index, index + text.length) + "</span>" + innerHTML.substring(index + text.length);
innerHTML.innerHTML = innerHTML;
}
}
.highlight {
background-color: red;
}
<html>
<body>
<div class="col-md-10 bordered selectborder fragment" id="torles">increase overall coder
</div>
<button onclick="highlight()">Highlight</button>
<div class="col-md-10 para bordered" id="inputText">
<strong><p>Significantly Reduce Costs and Improve Quality with an Experienced, Professional Global Coding Solution. Health Information Management (HIM) Directors and CFOs are seeking innovative ways to reduce expenses, maintain DNFB goals, and increase overall coder quality.</p></strong>
</div>
</body>
</html>
So, there were a couple things; but first, here's a working example.
function highlight() {
var text = document.getElementById("torles").textContent;//you want the text not the node
var inputText = document.getElementById("inputText");
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text);
if (index >= 0) {
innerHTML = innerHTML.substring(0, index) + "<span class='highlight'>" + innerHTML.substring(index, index + text.length) + "</span>" + innerHTML.substring(index + text.length);
inputText.innerHTML = innerHTML;//this line was incorrect
}
}
.highlight {
background-color: red;
}
<html>
<body>
<div class="col-md-10 bordered selectborder fragment" id="torles">increase overall coder</div><!-- make sure there's no line break after "coder"-->
<button onclick="highlight()">Highlight</button>
<div class="col-md-10 para bordered" id="inputText">
<strong><p>Significantly Reduce Costs and Improve Quality with an Experienced, Professional Global Coding Solution. Health Information Management (HIM) Directors and CFOs are seeking innovative ways to reduce expenses, maintain DNFB goals, and increase overall coder quality.</p></strong>
</div>
</body>
</html>
Anyway, there were three main things (and a typo). Firstly, you had a line break in your HTML after increase overall coder, and so it would try to find that string with the line break in the text, so it would just not find it.
Second, you mixed up what your variables actually mean; to start off, the text variable (which you misspelled as htext) was a node, not a string. Also, you tried to set the innerHTML of innerHTML, but your variable innerHTML was just a string. You want to set the innerHTML of the node (inputText in this case).

Truncating or Summarizing Text with html part in HTML

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!!

My HTML code is not being read on Javascript/JSON

So I'm doing a quote generator in Javascript in which the quote generates on click.
The code looks like this:
$("#getQuote").on("click", function(){
var i = Math.floor((Math.random() * quote.length));
$("#theQuote").html(quote[i] <\br> person[i]);
});
I'm trying to make a line break between the quote and the person who made the quote but it doesn't seem the recognize any code after quote[i].
I've also tried adding \n to the strings in my array for example:
var quote = ['"With great power, comes great responsibility." \n- Uncle Ben'];
but somehow \n is not read whereas the rest of the quote is.
1st $("#theQuote").html(quote[0] + '<br>' + person[0]); anything without wrap by ' or " are either number or variable, and .html take string as html, so you need concate them use +
2nd this way will also work, var quote = ['"With great power, comes great responsibility." <br> - TEST_1 Uncle Ben'];
var quote = ['"With great power, comes great responsibility." <br> - TEST_1 Uncle Ben'];
var person = ['TEST_2 Uncle Ben'];
$("#getQuote").on("click", function() {
//var i = Math.floor((Math.random() * quote.length));
$("#theQuote").html(quote[0] + '<br>' + person[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="getQuote">getQuote</button>
<br><br>
<div id="theQuote">N/A</div>
Change <\br> to <br> or <br />. This is according to the HTML5 standards.

a more graceful multi-line javascript string method

The only way I know how to print a huge string without using += is to use \ backslashes. ugly!
<div id="foo"></div>
<script type="text/javascript">
var longString = '<div id="lol">\
<div id="otherstuff">\
test content. maybe some code\
</div>\
</div>';
document.getElementById('foo').innerHTML = longString;
</script>
is there any way to do this where the longString is untainted? php has $foo = ''' long multiline string '''; I want this in javascript!
Anyone know of a better method for printing long, multi-line strings in javascript?
In general, the answer is: not in the language syntax. Though as Ken pointed out in his answer there are many work-arounds (my personal method is to load a file via AJAX). In your specific case though, I'd prefer creating a HTML constructor function so you can then define the HTML structure using javascript object literals. Something like:
var longString = makeHTML([{
div : {
id : "lol",
children : [{
div : {
id : "otherstuff",
children : [{
text : "test content. maybe some code"
}]
}]
}]
which I find to be much easier to handle. Plus, you this would allow you to use real function literals when you need it to avoid string quoting hell:
makeHTML([{
span : {
onclick : function (event) {/* do something */}
}
}]);
note: the implementation of makeHTML is left as exercise for the reader
Additional answer:
Found some old code after a quick scan through my hard disk. It's a bit different from what I suggested above so I thought I'd share it to illustrate one of the many ways you can write functions like this. Javascript is a very flexible language and there is not much that forces you to write code one way or another. Choose the API you feel most natural and comfortable and write code to implement it.
Here's the code:
function makeElement (tag, spec, children) {
var el = document.createElement(tag);
for (var n in spec) {
if (n == 'style') {
setStyle(el,spec[n]);
}
else {
el[n] = spec[n];
}
}
if (children && children.length) {
for (var i=0; i<children.length; i++) {
el.appendChild(children[i]);
}
}
return el;
}
/* implementation of setStyle is
* left as exercise for the reader
*/
Using it would be something like:
document.getElementById('foo').appendChild(
makeElement(div,{id:"lol"},[
makeElement(div,{id:"otherstuff"},[
makeText("test content. maybe some code")
])
])
);
/* implementation of makeText is
* left as exercise for the reader
*/
One technique if you have a big block is a <script> tag with an invalid type. It will be ignored by browsers.
<script type="text/x-my-stuff" id="longString">
<div id="lol">
<div id="otherstuff">
test content. maybe some code
</div>
</div>
</script>
<script type="text/javascript">
var longString = document.getElementById("longString").text;
document.getElementById('foo').innerHTML = longString;
</script>
A few somewhat unattractive options are discussed in the answers to this question.
You really could minimize this ugliness by creating your <div id="lol"> as HTML, and set its content with .innerHTML = "test content. maybe some code"
I don't like creating HTML in Javascript because of this exact issue, and instead use "template" elements which i simply clone then manipulate.
var lol = document.getElementById("template_lol").clone();
lol.firstChild.innerHTML = "code and stuff";
foo.appendChild(lol);
And this is the HTML:
<body>
<div>normal stuff</div>
<div style="display:none" id="templateBucket">
<div id="template_lol"><div class="otherstuff"></div></div>
</div>
</body>
This works too :
var longString =
'<div id="lol">' +
'<div id="otherstuff">' +
'test content. maybe some code' +
'</div>' +
'</div>';

Categories