Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript/CSS - find text with a particular expression and add css to it

I have the below text stored in a variable :

var string = "[~Folky Bee] How are you today?";

What I want to do is to add a class/style for only the text inside the delimiters [~Text here] which will have a final output like the following for example :

Folky Bee How are you today?

So far, I've tried to do the following :

var str = "[~Folky Bee] How are you today";
//Returns 1 (true) if the match is found (but I am getting wrong 
//results, maybe it's a wrong RegEx)
var n = str.search(/~/i);
//Then if the match is found add a color to it, but in this case I don't have 
//an id of that element so I can select it doing a .getElementById for example. 
//It's only a plain string.
like image 547
Folky.H Avatar asked Dec 04 '25 12:12

Folky.H


1 Answers

You could seach for brackets with tilde and take the inner group for the replacement with the style.

var string = "[~Folky Bee] How are you today?<br>[~Wham!] Fine!",
    replaced = string.replace(/\[~(.*?)\]/g, '<span class="foo">$1</span>');
    //                             ^^^        keeps value       ^^ 

console.log(replaced);
document.body.innerHTML += replaced;
.foo { font-weight: bold; }
like image 50
Nina Scholz Avatar answered Dec 07 '25 01:12

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!