Javascript highlighter in editable code - javascript

My goal is to have a highlighter made in JavaScript which change some word's color multiple times.
<div id="code" contenteditable="true">
hello world hello world
</div>
I want to have an outuput as : " Hello world Hello world "
How can I change the color of both "hello" using JavaScript?

By this following code, you can write a function to find the words and replace them with a colorful element (e.g or & ...)
$(function(){
// inquire element for run the function
var elem = $('#code');
// call highlighter method with the word and elemnet
highlighter('hello', elem);
});
function highlighter(word, elem){
// get inner html from passed element
var html = elem.html();
// define a new regex for replacing the word on specified element
var reg = new RegExp(word,"g");
// replace all found words with a new wrapped word
html = html.replace(reg, "<span class='highlight'>" + word +"</span>");
// set the specified element with new html
elem.html(html);
}
.highlight {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="code" contenteditable="true">
hello world hello world
</div>

You have to split your text to get each individual word, and then add each one in different 'span' tags which will have a 'fontWeight' property set to 'bold' if the word is 'hello'.
Here's an example:
var div = document.getElementById("code");
var text = div.innerText;
div.innerText = '';
text.split(' ').forEach(x => {
const span = document.createElement('span');
span.innerText = x + ' ';
if(x == 'hello')
span.style.fontWeight = 'bold';
div.appendChild(span);
})
Try out this fiddle

Related

extract text from html without loosing new lines

I use the following code to extract text from html.
var html = "first line. <div>second line. </div><div>third line.</div><div><br></div>"
var text = extractContent(html);
console.log("TEXT: " + text);
function extractContent(s) {
var span = document.createElement('span');
span.innerHTML = s;
return span.textContent || span.innerText;
}
the result of this code is the text without new lines. but I want the result to replace divs with "\n" like this:
first line."\n"second line. "\n" third line."\n"
Use s.replaceAll('&nbsp', '\\n'); to replace the linefeed.
Note: The backslash \ needs to be escaped with another \.
var html = "first line. <div>second line. </div><div>third line.</div><div><br></div>"
var text = extractContent(html);
console.log("TEXT: " + text);
function extractContent(s) {
var span = document.createElement('span');
s = s.replaceAll('&nbsp', '\\n');
span.innerHTML = s;
return span.textContent || span.innerText;
}
document.createElement is not necessary, you can use regexp alone to achieve this:
var html = "first line. <div>second line. </div><div>third line.</div><div><br></div>"
var text = extractContent(html);
console.log("TEXT: " + text);
function extractContent(s) {
/*
* /(<[^>]+>)+/gim <---- this regexp to match all html tags and replace them with \n,
* also merge empty content html tags into one \n
*
*/
return s.replace(/(<[^>]+>)+/gim, "\n");
}

how to add a h1 inside a div using javascript

I'm writing a HTML where I want to populate a h1 using Javascript. Here I'm able to populate text, but not the h1. Below is my code.
function getTheIncident(keyWord, text) {
showTheDiv();
console.log(keyWord + "\t" + text);
var e = document.getElementById('textResult');
e.innerHTML = text.replace('\^', '\'');
}
and this gives me the output as shown in the picture below.
MY aim is to add a h1 with content as Description. Basically like
<h1>Description</h1>
just above A procurement order has been placed for a RAM with 128 Gig
please let me know on how can I do this.
var h1= document.createElement('H1');
h1.innerHTML = "Description";
now add this element to a particular node you want
Just wrap the code to be added as HTML into an h1:
function getTheIncident(keyWord, text) {
showTheDiv();
console.log(keyWord + "\t" + text);
var e = document.getElementById('textResult');
e.innerHTML = "<h1>" + text.replace('\^', '\'') + "</h1>";
}
Create your tag by using createElement(), then prepend() it to your container where you want to have on first. Check below snippet for reference.
var h1Tag = document.createElement('H1');
h1Tag.innerHTML = "Your Title";
$('.output').prepend(h1Tag);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="output">
This div contains the output..
</div>
https://fiddle.jshell.net/LnkfLrev/1/ Something like this? you can use document.getElementById('placeholder').innerHTML = text; to set the text of you h1element
EDIT:
https://fiddle.jshell.net/LnkfLrev/2/
Sorry, I did not quiet get you question. I updated the fiddle so it works as an anwer
I created an H1 element with var h = document.createElement("H1");
then i set the Text and add it to the body
h.innerHTML = text;
document.body.appendChild(h);
hope this helps now

Insert value at position X

Hello I would like to add HTML on to a page once it finds particular text. I have managed to get the position I just can figure out how to add text
$(document).ready(function () {
var position = document.documentElement.innerHTML.indexOf('Gas');
//insert HTML at position
})
So since you already know where to insert, just do
var str = element.innerHtml;
element.innerHTML = str.substr(0, position - 1) + "<b>My HTML</b>" + str.substr(position);
Other way it would be to wrap that text in some element and do .insertBefore()
$(document).ready(function () {
var text = $('.my-text').html();
$('.my-text').html(text.replace(/Gas/, '<span id="my-unique-id">Gas</span>'));
var htmlToInsert = $('<b>', {text: 'Inserted text'});
htmlToInsert.insertBefore('#my-unique-id');
$('#my-unique-id').unwrap();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-text">
Abc def Gas Mesa Bas Ras
</div>

Match part of text inside of tag

I am in client side context.
I have this html:
<p>Text text \n other text </p>
I want to match only \n element inside paragraph, and replace only this with "br" tag.
I want to do this only inside tag "p" and for all match.
I supposed to use regex in javascript.
Thanks and sorry for my bad english.
Use html() method with callback and inside callback replace text using String#replace method.
$('p').html(function(i, htm) {
return htm.replace(/\\n/g, '<br>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Text text \n other text</p>
UPDATE 1 : If it's a string then use String#replace method.
console.log(
'<p>Text text \n other text</p>'.replace(/\n/g, '<br>')
)
UPDATE 2 : If the string contains other tag element and you just want to update the p tag then do something like.
var str = '<p>Text text \n other text</p>';
console.log(
// create a temporary div eleemnt
$('<div>', {
// set html content from string
html: str
})
// get all p tags
.find('p')
// iterate and replace \n
.html(function(i, htm) {
// replace \n with br tag
return htm.replace(/\n/g, '<br>')
})
// back to the temp div
.end()
// get it's updated html content
.html()
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
UPDATE 3 : With pure JavaScript by generating a temporary DOM element.
var str = '<p>Text text \n other text</p>';
// create a temporary div element
var div = document.createElement('div');
// set html content form string
div.innerHTML = str;
// get all p tags and convert into Array using Array.from
// for older browser use [].sclice.call instead
Array.from(div.getElementsByTagName('p'))
// iterate over p tags
.forEach(function(el) {
// update the html content
el.innerHTML = el.innerHTML.replace(/\n/g, '<br>')
});
// get updated html content
console.log(div.innerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use a for loop with getElementsByTagName:
for(i = 0; i < window.document.getElementsByTagName("p").length; i++){
window.document.getElementsByTagName("p")[i].innerHTML = window.document.getElementsByTagName("p")[i].innerHTML.replace(/\\n/g, "<br/>");
}
If this is inside a string and not inside the HTML, you can add it to a <div> element while handling it like this:
var myString = "<p>Text text \n other text </p>";
var div = document.createElement("div");
div.innerHTML = myString;
for(i = 0; i < div.getElementsByTagName("p").length; i++){
div.getElementsByTagName("p")[i].innerHTML = div.getElementsByTagName("p")[i].innerHTML.replace(/\\n/g, "<br/>");
}
myString = div.innerHTML;

add element with DOM model before paragraph

I want add new input text before paragraph. But it working opposite add after text.
What is wrong at this code?
I use document.getElementById("p1").insertBefore(node); with this aim, but without success. Why does this happen?
Code:
<html>
<head>
<title>Adding text to a page</title>
<script>
function addText() {
var sentence=document.form1.sentence.value;
var node=document.createTextNode(sentence + " ");
document.getElementById("p1").insertBefore(node);
}
</script>
</head>
<body>
<h1>Create Your Own Content</h1>
<p id="p1">Using the W3C DOM, you can dynamically
add sentences to this paragraph. Type a sentence
and click the Add button.</p>
<form name="form1">
<input type="text" name="sentence" size="65">
<input type="button" value="Add" onClick="addText();">
</form>
</body>
</html>
Question:
How to solve this issue?
The insertBefore method needs to be called on the parent node (in which you want to insert), just like appendChild:
var node=document.createTextNode(sentence + " ");
var p1 = document.getElementById("p1");
p1.parentNode.insertBefore(node, p1);
If you want to add sentences to the paragraph instead of before it (right into the <body>), you would use this:
p1.appendChild(node); // insert at the end
// or
p1.insertBefore(node, p1.firstChild); // insert at the beginning
You could
Grab the new sentence.
Grab the original content.
Put them both together in a variable.
Clear the element.
Slap it back in.
Like so:
var addText = function() {
var sentence = document.form1.sentence.value;
var node = document.createTextNode(sentence + " ");
var el = document.getElementById("p1");
var original = el.innerHTML;
var newPara = sentence + ". " + original;
el.innerHTML = "";
el.innerHTML = newPara;
}
jsFiddle
Mind you, this is alot of steps, but hey, a million ways to skin a cat.
Of course you could always shorten all of that code up there to this:
var addText = function() {
document.getElementById("p1").innerHTML = document.form1.sentence.value + ". " + document.getElementById("p1").innerHTML;
}
new jsFiddle

Categories

Resources