Replace a word in a string with a styled span dynamically - javascript

I'm trying to do something pretty simple, but I'm embarrassed to say that I can't figure it out. I'm looking to find words in a string that start with '#' or '#' and give the word a styling color of blue. The string is coming from an API, so I can't initially set the word inside a span.
I've tried used string replace() with a regular expression to find words that start with '#', and replace it with a span that has the same text, but with the color blue. I've seen this answer pop up throughout SO, but when I try to implement it the entire span is rendered as text, instead of just the text itself. Moreover, the text doesn't have the color changed to blue– I'm getting <span style='color: blue;'>#user42</span> as text, instead of just #user42.
I used a different regexp to remove the spans from being rendered to the page as text but that just seems like I missing something and doing extra work to remedy what I'm unaware of.
Here's what I've tried to do to solve it without using .replace(), but I'm unable to insert the newly created span into the same position as the word being removed.
tweetText[0].split(' ').forEach((word) => {
if (word.innerText.startsWith('#') || word.innerText.startsWith('#')) {
const span = document.createElement('span');
span.innerText = word;
span.style.color = 'blue';
}
});
How can I use replace() to find a word that starts with '#' or '#' and replace it with the same text, but with a different color?

Added color, background-color, padding, and border-radius to look good.
const result = document.querySelector(".result");
function colorizeSelectedText(str) {
const result = str
.split(" ")
.map((word) => {
if (word.startsWith("#") || word.startsWith("#")) {
return `<span style='color: blue; background: bisque; padding: 0.25rem; border-radius: 4px;'>${word}</span>`;
}
return word;
})
.join(" ");
return result;
}
const text = colorizeSelectedText(
"This is #test for the #color that is not colored"
);
result.innerHTML = text;
<div class="result"></div>

Related

Javascript/jQuery change word color by specific some text contains

I have a simple question with jQuery Css.
I would like to change color of my text by specific word contains using jQuery.
I have example like this:
<div class="me">I'm Groot</div>
I'm <-- will be always black color
Groot <-- will be always green color and Groot sometimes can be change with another word.
How can I do that with jQuery or javascript?
You could replace all occurrences of your specific text snippets with custom styled html elements:
const yourName = "Groot";
const element = document.querySelector(".me");
element.innerHTML = element.innerHTML
.replace("I'm", `<span class="black-class">I'm</span>`)
.replace(yourName, `<span class="green-class">${yourName}</span>`);
Alternatively you can also make everything green except the I'm like this:
.me {
color: green;
}
element.innerHTML = element.innerHTML
.replace("I'm", `<span class="black-class">I'm</span>`);
This way not only Groot is colored green but everything inside of the div. That way your JavaScript doesn't need to know the name.
Just group them like so
:
<div class="me">I'm <span id="changer">Groot</span></div>
Then for CSS, style it like so:
#changer {
color: green;
}
Then to change with javascript:
document.getElementById("changer").innerHTML = "Changed";
Which of course you can add a setTimeout to change continuously
Edit:
No problem, since the only part changing is "Groot" part,
So:
var changing = "Groot";
$('.me').text(`I'm <span id="changer">${changing}</span>`);
// then from here the value of the $('#changer') can be accessed and changed
$('#changer').text('Not Groot');

JS Chrome Plugin - find text located in currently active tab

The code below is based on the samples provided in this example:
StackOverflow Question
I am no good with JS but would like to adjust this code to highlight not just a number located in a on the website, but rather highlight specific text located anywhere in the active tab, by either changing the font color or the highlighting the text. How can I do that?
Appreciate any help, I am new to JS and a little lost.
Thanks,
A2k
EDIT:
To clarify, I want to highlight the words Apple, Banana, etc. when they are located ANYWHERE in the active tab, not necessarily in a table or a td. This means the words can just as well be in a paragraph of text, in a label, an input field, etc.
highlightText.js
// keyword to highlight
var keywordArray = ["apple","banana","orange"];
keywordArray.forEach(function(v){
var num = "(" + v + ")";
// Select the '<td>' that contains the number we are looking for
var td = $('td.col-question:contains('+num+')');
// Make sure that this number exists
if(td.length > 0){
// Now that we have it we need to single out the number and replace it
var span = td.html().replace(num,'<span class="highlight-num">'+num+'</span>');
var n = td.html(span);
}
// Now instead of '(1000)' we have
// '<span class="highlight-num">(1000)</span>'
// We will color it in the css file
});
highlight.css
span.highlight-num{
background-color: rgb(100, 255, 71);
}
Your issue is with:
var num = "(" + v + ")";
By doing this you are checking if the fruit (apple), (banana) or (orange) is in your table. Instead, you can remove this to check whether apple, banana or orange is contained in your table.
You can instead use a regular expression to replace the keywords if they appear with spans around them to highlight them.
This does have its downsides however, as it won't work properly with text inputs as the markup will not be rendered as HTML.
See working example below:
$(function() {
const keywordArray = ["apple", "banana", "orange"];
const body = $('body');
body.html((_, innerHTML) =>
innerHTML.replace(new RegExp(`(${keywordArray.join('|')})`, 'g'), '<span class="highlight-num">$1</span>')
);
});
span.highlight-num {
background-color: rgb(100, 255, 71);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<p>The big apple is big</p>
<em>The orange <strong>orange</strong> is orange</em>
<br />
<span>The green grape is green</span>
<h4>The banana is a banana</h4>
</body>

Javascript function to search DOM and change color of words in an array

I've got an array of words like
const conjunctions = ["for, and, nor, but, or, yet, so"]
and on page load, I want to run a function that checks the text of the #page id and change the color of those words to red. I was trying to use the fontcolor method, but it doesn't seem to work? https://www.w3schools.com/jsref/jsref_fontcolor.asp
Thanks in advance for helping.
To do this you will need to parse the innerHTML of the element with id page and then replace it with new markup that contains child elements wherever there is a matched word.
Here is how I would do it:
const words = ["for", "and", "nor", "but", "or", "yet", "so"];
const el = document.getElementById("page");
const markup = el.innerHTML.split(" ").map((word) => {
if (words.includes(word)) {
return '<span class="highlight">' + word + '</span>';
} else {
return word;
}
}).join(" ");
el.innerHTML = markup;
.highlight {
color: red;
}
<html>
<head>
</head>
<body>
<p id="page">
This is some text, and I want it to display some style.
</p>
</body>
</html>
The word matching is quite primitive here, considering that I forced a "split" on all spaces in the paragraph. This becomes unusable if you want to consider words that may be up next to other characters in the body of the page, such as commas, other markup, tabs, newlines, etc.

Javascript add class to selected text, not first occurrence of the selected text

I want to add a class (and later on to send that string to php) to a text with javascript. Whenever I try to do that, the code is adding the class to the first occurrence of my selection, not to the actual selection. Keep in mind that I want to send that EXACT selection to php (and put it in a database as well so it keep that class even after refresh).
JQ
$("#highlight").click(function(){
paraval = $('#para').html();
sel = window.getSelection();
newst = '<a class="selectedText">' + sel + '</a>';
newvalue = paraval.replace(sel, newst);
$('#para').html(newvalue);
});
HTML
<p>Will only highlight if text is selected from comment class div only</p>
<div class="comment" id="para" contenteditable="true">Here goes some text Here goes some text Here goes some text Here goes some text
Some other text</div>
<input type="button" value="Highlight" id="highlight"/>
CSS
.selectedText{
background-color:yellow;
}
.comment{
border: solid 2px;
}
.comment::selection {
background-color: yellow;
}
example here: http://jsfiddle.net/zq1dqu3o/3/
try to select the last occurrence of the word "text". the first one will get the class "selectedText"...
thanks
Call me lazy, but if you don't mind span being you selection marker tag, you can use rangy's cssApplier class.
var cssApplier;
$(document).ready(function() {
rangy.init();
cssApplier = rangy.createCssClassApplier(
"selectedText", {normalize: true,
applyToEditableOnly:true});
});
$("#highlight").click(function(){
if(cssApplier != undefined)
{
cssApplier.toggleSelection();
}
});
I use applyToEditableOnly here to make it only work in that specific div. (I'm not sure how cross-browser compatible that particular setting is. Worked in Chrome and Firefox though.) This uses position rather than selection text to decide what to mark.
JS Fiddle Here: http://jsfiddle.net/zq1dqu3o/7/
You can get the last occurence with lastIndexOf() and proceed like this:
$("#highlight").click(function(){
paraval = $('#para').text();
sel = "text";
var n = paraval.lastIndexOf(sel);
var before = paraval.substring(0,n);
newst = before + '<a class="selectedText">' + sel + '</a>';
newvalue = paraval.replace(paraval, newst);
$('#para').html(newvalue);
});
Just created a fiddle for it: Replacing last occurence
Note: This quick example is only working because the word you want to highlight is at the last position of the text, but you can check out if this solution is ok for your request. In case the last occurence of the word is elsewhere, just create a variable "after" that contains the text following the last occurence of the word to the end.
Have just provided an example for this in updated fiddle: Replacing last occurence update
with following update to previous code:
var after = paraval.substring(n + sel.length, paraval.length);
newst = before + '<a class="selectedText">' + sel + '</a>' + after;

Change style of all occurrences of a string

I want my site title to display in a unique font from the rest of the content every time it appears in a heading, for branding reasons. For simplicity, let's pretend my special font is Courier and my company is called SparklePony. So, a line like,
<h1 class="title">SparklePony Board of Directors</h1>
would show a headline with the word SparklePony in Courier and Board of Directors in my site default font, Arial. (Yes, I know this would be hideous.)
I've tried using a jQuery string replacement, but I don't want to replace the string, I just want to see it in Courier (adding a class to just that word, or something of the like.) Replacing SparklePony with <span class="sparkle-pony">SparklePony</span> caused the whole ugly string with tags and everything to show on my site, rather than adding the class.
Am I doing something wrong with my string replace, or is there a better way to style all occurrences of a string?
You can do it like this - specifying the selector you want - #('h1') or by class.
$('.title').html(function(i,v){
return v.replace(/SparklePony/g,'<span class="sparkle">SparklePony</span>');
});
​
http://jsfiddle.net/cQjsu/
Without seeing the code (which would be kinda important in questions like this), best guess is that you're using .text() instead of .html() which would parse the HTML correctly.
It could do with some tidying, but this may be a good starting point: http://jsfiddle.net/c24w/Fznh4/9/.
HTML
<div id="title">Highlight this blah blah HiGhLiGhT THIS blah</div>
<button id="clickme">Click to highlight text</button>
CSS
#title{
font-family: sans-serif;
font-size: 20pt;
margin: 30px 0;
}
span.highlight{
color: #09f;
font-weight: bold;
}
JavaScript
function highlightText(element, phrase, allOccurrences, caseSensitive){
var modifiers = (allOccurrences ? 'g' : '') + (caseSensitive ? '' : 'i');
var text = element.innerHTML;
element.innerHTML = text.replace(new RegExp(phrase, modifiers), function(match){
return '<span class="highlight">' + match + '</span>';
});
}
var button = document.getElementById('clickme');
var el = document.getElementById('title');
button.onclick = function(){
highlightText(el, 'highlight this', true, false);
button.onclick = null;
};
Try Something like that :
$.each($(".title"),function({
$(this).html($(this).html().replace("SparklePony","<span class='sparkle-pony'>SparklePony</span>"))
});
Nice and short:
var $body = $("body");
$body.html($body.html().replace(/SparklePony/ig, "<span class='cool'>SparklePony</span>"));​
But keep in mind that $("body") is a very costly selector. You should consider a more precise parent target.
Demo here (fiddle)

Categories