Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript string replacement (a more elegant way)

Tags:

javascript

I have a string:

var myString = 'Some text {{more text}} next text';

And I am trying to replace {{ and }} with <span> and </span>.

I have done this by doing:

var myString = 'Some text {{more text}} next text';
myString = myString.replace(/\{\{/, '<span>');
myString = myString.replace(/\}\}/, '</span>');
console.log(myString);

However this seems messy, is there an approach that is more elegant?

like image 635
beingalex Avatar asked Jun 09 '26 15:06

beingalex


2 Answers

Regex isn´t necessary here, you shorter and cleaner

myString = myString.replace('{{', '<span>');
myString = myString.replace('}}', '</span>');

Another possibility (thx @Artyom Neustroev for comment):

myString = myString.replace('{{', '<span>').replace('}}', '</span>');
like image 96
pavel Avatar answered Jun 12 '26 06:06

pavel


If you want to use regex, here you have an example;

var myStrippedStr = myString.replace(/(.*){{(.*)}}(.*)/, '$1<span>$2</span>$3');
like image 33
Kokkie Avatar answered Jun 12 '26 07:06

Kokkie



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!