Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
Replace array of signs inside a span

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.
about 4 years ago · Juan Pablo Isaza Report

0

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>"));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!