Change style of all occurrences of a string - javascript

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)

Related

Append text of different style

Hi is there a way to make the appended "YAY" be of a different style from the "I am happy" text? eg. bigger font-size/ bolded.
document.getElementById("appendButton").onclick = function() {
document.getElementById("happy").innerHTML += " YAY";
}
<p id="happy">I am happy</p>
<button id="appendButton">Click here to cheer!</button>
I've tried to give it an id with span, but then the button won't append anything. Would appreciate any help thanks!
You won't be able to use an id because ids must be unique (which means you can't have more than one on a page and expect the correct output).
Add a class instead.
Note 1: I've used the more modern addEventListener method here.
Note 2: It's also worth mentioning that concatenating HTML strings to innerHTML is considered bad practice. insertAdjacentHTML is the better alternative.
const button = document.getElementById('appendButton');
const happy = document.getElementById('happy');
button.addEventListener('click', handleClick, false);
function handleClick() {
happy.innerHTML += '<span class="yay"> YAY</span>';
}
.yay { color: blue; font-weight: 600; }
<p id="happy">I am happy</p>
<button id="appendButton">Click here to cheer!</button>
You can append a span element with a class, then style it with CSS:
document.getElementById("appendButton").onclick = function() {
document.getElementById("happy").innerHTML += "<span class='large'>YAY</span>";
}
.large{
font-size:20px;
font-weight:bold;
}
<p id="happy">I am happy</p>
<button id="appendButton">Click here to cheer!</button>

Replace a word in a string with a styled span dynamically

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>

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>

Underline some characters in a String

I have the following problem:
My JavaScript code shows a display value this way:
d3.select("#" + uiElement).html("")
.append("span").attr("class", "displayvalue").html(stringToUse);
stringtoUse is the value to show, my issue is to underline that string, but some times, it's not required underline all the string but all except the first character of it.
In your opinion what's the best way to do so?
Use CSS first-letter pseudo element. Make your all text underlined and then apply css to it as:
#element::first-letter
{
text-decoration:none !important:
}
Reference to use.
By simple pure javascript:
var text = document.getElementById("element").innerHTML;
document.getElementById("element").innerHTML = text.substring(0,1)+"<u>"+text.substring(1)+"</u>";
This will allow you to format any javascript innerHTML using CSS directly, without hassling around in javascript:
The javascript:
function test(){
document.getElementById('pp').innerHTML = 'here is pp';
document.getElementById('qq').innerHTML = 'here is qq';
}
The HTML:
<p style = 'whatever'>
<a id = 'pp'></a>
<a id = 'qq' style = 'color:red; text-decoration: underline;' ></a>
</p>
<script>
test()
</script>
This works with or without a wrapper like <p>.

Categories