How to replace a text with coloured text using javascript - javascript

I am having this text in text area.
{color:#c91d1d}Hello{color}
when it is submitted, i want the text between {} tags to be shown in color specified inside {} tag with color:
how can i do so in javascript

use javascript built in function to extract color code
var colorValue = str.substring(7, 7);
it extract 7 characters from 7th position.
now change the color using:
document.getElementById("myH2").style.color = colorValue;
I hope this will work

You can use a regex like
$('#input').on('input', function() {
$('#result').html(this.value.replace(/\{color:(.*?)\}(.*?)((\{color\})|$)/g, '<span style="color:$1">$2</span>'));
}).triggerHandler('input');
textarea {
width: 100%;
min-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="input">{color:#c91d1d}Hello{color} - {color:green}hi{color}</textarea>
<div id="result"></div>

Arun is right, and if you just need to get "Hello" from "{color:#c91d1d}Hello{color}" string you can do it like this
var justtext="{color:#c91d1d}Hello{color}".match(/\{.*\}(.*)\{.*\}/)[1];
For full replacement of text in textarea here's the code. Suppose textarea has id attribute "textarea1", change it with your id.
var textwithcolor =$("#textarea1").text();
var justtext=textwithcolor.match(/\{.*\}(.*)\{.*\}/)[1];
$("#textarea1").text(justtext);

this is how it can be done
No need to use regular expressions.
try this
var str = $('#t').text();
var res = str.substring(7, 14);
newstr = str;
while (newstr.indexOf("{color}") > -1) {
newstr = newstr.replace("{color}", "</div>");
}
while (newstr.indexOf("{color:") > -1) {
newstr = newstr.replace("{color:", "<div style='color:");
newstr = newstr.replace("}", "'>");
}
document.getElementById("t").innerHTML = newstr;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="t">{color:#c91d1d}Hello{color}
{color:red}How{color} {color:yellow}are{color} {color:green}you{color}
</div>

Related

Javascript - How to style specific word in a string of text?

I have a string of text here that will be dynamically generated to be one of the following:
<h1 id="headline">"Get your FREE toothbrush!"</h1>
OR
<h1 id="headline">"FREE floss set and dentures!"</h1>
Since this will be dynamically generated I won't be able to wrap a <span> around the word "FREE" so I want to specifically target the word "FREE" using Javascript so that I can style it with a different font-family and font-color than whatever styling the <h1> is set to. What methods do I use to go about doing this?
You can search and replace the substring 'FREE' with styled HTML. If 'FREE' occurs more than once in the string you may need to use regex (unless you don't need to support Internet Explorer). See How to replace all occurrences of a string?
In your case:
let str = '<h1 id="headline">"FREE floss set and dentures!"</h1>'
str = str.replace(/FREE/g, '<span color="red">FREE</span>');
The property you are looking for is innerHTML, look the following example:
var word = document.getElementById('word');
function changeWord(){
word.innerHTML = "another";
word.style.backgroundColor = 'black';
word.style.color = 'white';
}
<h1 id="headline">
<span id="word">some</span> base title
</h1>
<button onClick="changeWord()">
change
</button>
Here is a working example using slice and some classic concatenation.
EDIT: Code for the second string is also included now.
//get headline by id
var headline = document.getElementById("headline");
//declare your possible strings in vars
var string1 = "Get your FREE toothbrush!"
var string2 = "FREE floss set and dentures!"
//declare formatted span with "FREE" in var
var formattedFree = "<span style='color: blue; font-style: italic;'>FREE</span>"
//target positions for the rest of your string
var string1Position = 13
var string2Position = 4
//concat your vars into expected positions for each string
var newString1 = string1.slice(0, 9) + formattedFree + string1.slice(string1Position);
var newString2 = formattedFree + string2.slice(string2Position)
//check if strings exist in html, if they do then append the new strings with formatted span
if (headline.innerHTML.includes(string1)) {
headline.innerHTML = newString1
}
else if (headline.innerHTML.includes(string2)) {
headline.innerHTML = newString2
}
<!-- As you can see the original string does not have "FREE" formatted -->
<!-- Change this to your other string "FREE floss set and dentures!" to see it work there as well -->
<h1 id="headline">Get your FREE toothbrush!</h1>
You can split the text and convert the keyword "FREE" to a span element. So you can style the keyword "FREE". This method is safe because does not alter any non-text html element.
var keyword = "FREE";
var headline = document.getElementById("headline");
var highlight, index;
headline.childNodes.forEach(child => {
if (child.nodeType == Node.TEXT_NODE) {
while ((index = child.textContent.indexOf(keyword)) != -1) {
highlight = child.splitText(index);
child = highlight.splitText(keyword.length);
with(headline.insertBefore(document.createElement("span"), highlight)) {
appendChild(highlight);
className = 'highlight';
}
}
}
});
.highlight {
/* style your keyword */
background-color: yellow;
}
<div id="FREE">
<h1 id="headline">"Get your FREE toothbrush! FREE floss set and dentures!"</h1>
</div>

Multiple String Manipulation using js

I have a text area that I will paste some data in for example like so
01-06-2019 <!-- mm-dd-yyyy -->
01-07-2019
01-08-2019
01-09-2019
01-10-2019
And when I click submit all the text inside the text box to give an output below something like this
06/01/2019 <!-- dd/mm/yyyy -->
07/01/2019
08/01/2019
08/01/2019
10/01/2019
I have managed to this on python using this code
filepath = ('date.txt')
f = open("newdate.txt", "w+")
new = []
with open(filepath) as fp:
for line in fp:
line = line.strip('\n')
new = line.split("-")
f.write(new[1] + "/" + new[2] + "/" + new[0] + "\n")
print(new[1] + "/" + new[2] + "/" + new[0] + "\n")
f.close()
I am new to JavaScript and jQuery so wondering how can i achieve that in jQuery
You can register an onsubmit listener on your form and then in the handler, perform your logic of parsing the text area's value.
The following snippet is an example of how to do that:
// Register 'submit' event listener
document.querySelector('#form')
.addEventListener('submit', e => {
// Prevent default action so that page doesn't refresh
e.preventDefault();
// Get the text from the textarea
let text = document.querySelector('#text').value;
// Split the lines
let converted = text.split('\n')
// Convert each line
.map(str => {
// Extract the date parts
let [mm, dd, yyyy] = str.split('-');
// Return the desired format by joining the date parts with /
return [dd, mm, yyyy].join('/');
});
// Print result to console
console.log(converted);
});
<form id="form">
<textarea id="text"></textarea>
<button type="submit">submit</button>
</form>
use following regexp-replace for textarea value
value.replace(/(-)(?=\d)/g,'/')
The (-)(?=\d) will find all dashes '-' preceding the number
function submit() {
let r=data.value.replace(/(-)(?=\d)/g,'/');
console.log(r);
}
textarea { width: 200px; height: 100px; }
button { display: block }
<textarea id="data">
01-06-2019 <!-- mm-dd-yyyy -->
01-07-2019
01-08-2019
01-09-2019
01-10-2019
</textarea>
<button onclick=submit()>Submit</button>
You don't really need any jQuery for this just a little regex should work.
const datesArr = [
'01-06-2019',
'01-07-2019',
'01-08-2019',
'01-09-2019',
'01-10-2019',
]
const newDates = []
const regex = /(\d\d)-(\d\d)-(\d{4})/
for (let date of datesArr) {
newDates.push(date.replace(regex, '$2/$1/$3'))
}
console.log(newDates)
function convertToFormat(data) {
var _dataSplit = data.split('\r\n');
var _length = _dataSplit.length;
var _finalData = '';
for (var i=0;i<_length;i++) {
var _dataDSplit = _dataSplit[i].split('-');
_finalData += _dataDSplit[1]+'/'+_dataDSplit[0]+'/'+_dataDSplit[2]+'\r\n';
}
return _finalData;
}
You can get the text area value on clicking submit like the below snippet. You can do your date manipulation (Learn some string manipulation to do the formatting. Refer - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
function formatText() {
var textAreaValue = $('#my-text').val();
// Do the necessary formatting here
var formattedText = 'test';
$('#my-text').val(formattedText);
}
.btn {
display: block;
width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<textarea id="my-text"></textarea>
<button class="btn" onClick="formatText()">Submit</button>
</div>
Try using regex replace.
Regex demo here
let dates = document.getElementById('dates');
console.log(dates.value.replace(/(\d{2})-(\d{2})-(\d{4})/g, '$2/$1/$3'))
<textarea id="dates" rows="6" cols="30">
01-06-2019 <!-- mm-dd-yyyy -->
01-07-2019
01-08-2019
01-09-2019
01-10-2019
</textarea>

Adding br tag in innerHTML between text and image

In my javascript program I have created div and added image and some hardcoded text in div by using innerHTML. But I am trying to add dynamic br tag between text and image. First text should be displayed then want to line break and then image should be displayed. So created br and added but somehow it doesn't work. Can anyone correct me ?
code:
function useInnerHTML() {
var movieText2 = prompt("One of my favourite movies");
var textNode = document.createTextNode(movieText2);
ele.appendChild(textNode);
document.body.appendChild(ele);
var newDiv2 = document.createElement("div");
var br = document.createElement("br");
newDiv2.className = "green";
var pic = "A picture is worth a thousand words";
var text2 = '<img src=\'https://i.stack.imgur.com/meXYL.png\'>';
newDiv2.innerHTML = pic + text2;
document.body.appendChild(newDiv2);
document.body.appendChild(br);
}
useInnerHTML();
.pink {
background-color: pink;
}
.green {
background-color: #71e887;
}
my output:
![output][1]
Simply use
pic = "A picture is worth a thousand words <br>";
since by using .innerHTML the <br> tag will not be escaped and actually embedded into the HTML as a breakline Element.
Or
Use Template strings and insertAdjacentHTML
function addNewMovie() {
var movieName = prompt("One of my favourite movies").trim(); // Trim it!
if(!movieName) return; // do nothing if empty!
var movieTemplate = `
<div class="movie">
<h1>${movieName}</h1>
<div class="green">
A picture is worth a thousand words<br>
<img src='//placehold.it/100x100/0bf'>
</div>
</div>
`;
document.body.insertAdjacentHTML("beforeend", movieTemplate);
}
<button onclick="addNewMovie()">ADD NEW MOVIE</button>
...cleaner, nicer.
You are adding the <br> after the picture, try doing it like this:
newDiv2.innerHTML = pic + br + text2;
document.body.appendChild(newDiv2);

Simple JS code for highlighting search text in a paragraph

I am trying to rewrite this code to suit my needs, but I am lost in all the replacing magic that the auther of the Fiddle does. Here's my modified fiddle.
My goal is to find all occurrances of "a" letter in the paragraph and highlight them. I just can't figure out why my letters are just being replaced by 1$ instead of being highlighted. Can anyone help me with this ?
HTML
<div id="searchtext">
<p>I want to highlight all "a" letters in this paragraph</p>
</div>
JS
$(document).ready(function() {
var text = 'a';
var query = new RegExp(text, "gim");
var e = document.getElementById("searchtext").innerHTML;
var enew = e.replace(/(<span>|<\/span>)/igm, "");
document.getElementById("searchtext").innerHTML = enew;
var newe = enew.replace(query, "<span>1$</span>");
document.getElementById("searchtext").innerHTML = newe;
});
CSS:
#searchtext span {
background-color: #FF9;
color: #555;
}
Use \$& instead
$(document).ready(function() {
var text = 'a';
var query = new RegExp(text, "gim");
var e = document.getElementById("searchtext").innerHTML;
var enew = e.replace(/(<span>|<\/span>)/igm, "");
document.getElementById("searchtext").innerHTML = enew;
var newe = enew.replace(query, "<span>\$&</span>");
document.getElementById("searchtext").innerHTML = newe;
});
#searchtext span {
background-color: #FF9;
color: #555;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="searchtext">
<p>I want to highlight all "a" letters in this paragraph</p>
</div>
More information about $&

Extract the text out of HTML string using JavaScript

I am trying to get the inner text of HTML string, using a JS function(the string is passed as an argument). Here is the code:
function extractContent(value) {
var content_holder = "";
for (var i = 0; i < value.length; i++) {
if (value.charAt(i) === '>') {
continue;
while (value.charAt(i) != '<') {
content_holder += value.charAt(i);
}
}
}
console.log(content_holder);
}
extractContent("<p>Hello</p><a href='http://w3c.org'>W3C</a>");
The problem is that nothing gets printed on the console(*content_holder* stays empty). I think the problem is caused by the === operator.
Create an element, store the HTML in it, and get its textContent:
function extractContent(s) {
var span = document.createElement('span');
span.innerHTML = s;
return span.textContent || span.innerText;
};
alert(extractContent("<p>Hello</p><a href='http://w3c.org'>W3C</a>"));
Here's a version that allows you to have spaces between nodes, although you'd probably want that for block-level elements only:
function extractContent(s, space) {
var span= document.createElement('span');
span.innerHTML= s;
if(space) {
var children= span.querySelectorAll('*');
for(var i = 0 ; i < children.length ; i++) {
if(children[i].textContent)
children[i].textContent+= ' ';
else
children[i].innerText+= ' ';
}
}
return [span.textContent || span.innerText].toString().replace(/ +/g,' ');
};
console.log(extractContent("<p>Hello</p><a href='http://w3c.org'>W3C</a>. Nice to <em>see</em><strong><em>you!</em></strong>"));
console.log(extractContent("<p>Hello</p><a href='http://w3c.org'>W3C</a>. Nice to <em>see</em><strong><em>you!</em></strong>",true));
One line (more precisely, one statement) version:
function extractContent(html) {
return new DOMParser()
.parseFromString(html, "text/html")
.documentElement.textContent;
}
textContext is a very good technique for achieving desired results but sometimes we don't want to load DOM. So simple workaround will be following regular expression:
let htmlString = "<p>Hello</p><a href='http://w3c.org'>W3C</a>"
let plainText = htmlString.replace(/<[^>]+>/g, '');
use this regax for remove html tags and store only the inner text in html
it shows the HelloW3c only check it
var content_holder = value.replace(/<(?:.|\n)*?>/gm, '');
Try This:-
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function extractContent(value){
var div = document.createElement('div')
div.innerHTML=value;
var text= div.textContent;
return text;
}
window.onload=function()
{
alert(extractContent("<p>Hello</p><a href='http://w3c.org'>W3C</a>"));
};
</script>
</body>
</html>
For Node.js
This will use the jsdom library, since node.js doesn't have dom features as in browser.
import * as jsdom from "jsdom";
const html = "<h1>Testing<h1>";
const text = new jsdom.JSDOM(html).window.document.textContent;
console.log(text);
Use match() function to bring out HTML tags
const text = `<div>Hello World</div>`;
console.log(text.match(/<[^>]*?>/g));
You could temporarily write it out to a block level element that is positioned off the page .. some thing like this:
HTML:
<div id="tmp" style="position:absolute;top:-400px;left:-400px;">
</div>
JavaScript:
<script type="text/javascript">
function extractContent(value){
var div=document.getElementById('tmp');
div.innerHTML=value;
console.log(div.children[0].innerHTML);//console out p
}
extractContent("<p>Hello</p><a href='http://w3c.org'>W3C</a>");
</script>
Using jQuery, in jQuery we can add comma seperated tags.
var readableText = [];
$("p, h1, h2, h3, h4, h5, h6").each(function(){
readableText.push( $(this).text().trim() );
})
console.log( readableText.join(' ') );
you need array to hold values
function extractContent(value) {
var content_holder = new Array();
for(var i=0;i<value.length;i++) {
if(value.charAt(i) === '>') {
continue;
while(value.charAt(i) != '<') {
content_holder.push(value.charAt(i));
console.log(content_holder[i]);
}
}
}
}extractContent("<p>Hello</p><a href='http://w3c.org'>W3C</a>");

Categories

Resources