Home > other >  Replace array of signs inside a span
Replace array of signs inside a span

Time:01-09

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'>&nbsp;:</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'>&nbsp;$&</span>");
console.log(result)

Here,

  • signs.sort((a, b) => b.length - a.length) sorts the signs array items by length in descending order
  • signs.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 regex
  • new 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'>&nbsp;"   sign   "</span>");

or if you want to use regex it would be overcomplicated:

result = signs.map(sign => sign.replace(/(. )/g, "<span class='some-class'>&nbsp;$1</span>"));
  •  Tags:  
  • Related