I want to wrap each sign in the given array inside a span tag to be able to render it to DOM:
Here is the signs array:
const signs = ['!!', '?!', '!?', '...', '..', '.', '?', '!', ':', '؟!', '!؟', '؟'];
I can replace each sign individually like this:
result = result.replace(/([\:])/g, "<span class='some-class'> :</span>");
The above code put : sign inside a span.
How can I do this for all of array signs without hard coding them?
CodePudding user response:
You can use
let result = "!! ?! !? ... .. . ? ! : ؟!, !؟ ؟";
const signs = ['!!', '?!', '!?', '...', '..', '.', '?', '!', ':', '؟!', '!؟', '؟'];
signs.sort((a, b) => b.length - a.length);
const regex = new RegExp(signs.map(x =>
x.replace(/[-\/\\^$* ?.()|[\]{}]/g, '\\$&')).join('|'),
'g');
result = result.replace(regex, "<span class='some-class'> $&</span>");
console.log(result)
Here,
signs.sort((a, b) => b.length - a.length)
sorts thesigns
array items by length in descending ordersigns.map(x => x.replace(/[-\/\\^$* ?.()|[\]{}]/g, '\\$&'))
- escapes all the special chars in the items to make them match literal chars inside a regex....join('|')
- creates an alternation regexnew RegExp(..., 'g')
- defines a RegExp object that matches all pattern occurrences in the string$&
in the replacement pattern inserts the match value.
CodePudding user response:
You could use:
result = signs.map(sign => "<span class='some-class'> " sign "</span>");
or if you want to use regex it would be overcomplicated:
result = signs.map(sign => sign.replace(/(. )/g, "<span class='some-class'> $1</span>"));