3

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.
3
  • you probably forgot to add some relevant code like the regexp you are using Commented Sep 24, 2018 at 15:58
  • 1
    So match the brackets and text inside and do a replacement? Commented Sep 24, 2018 at 15:59
  • @epascarello that's the thing, I wasn't able to match those brackets and what's more challenging is adding css to what's inside because it's whole plain text Commented Sep 24, 2018 at 16:01

1 Answer 1

3

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; }

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answers; however, the following is not clear for me : <span class="foo">$1</span> it seems that if I replace it with any other value it still does not change anything
what does not change? the original string? (string are immutable.) which value do you like to replace?
Sorry, my bad, after your last edit it made things clear for me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.