Home > Software engineering >  surround each of the array items with the `^` sign excluding repeated ones
surround each of the array items with the `^` sign excluding repeated ones

Time:11-23

Thanks to @Konrad we can surround each of the array items with the ^ sign like this:

const signs = [',', '!!', '?!', '!?', '...', '..', '.', '?', '؟!', '!؟', '!', '؟', ':'];

const input = 'this is, a text?'

const str = signs.map(e => e.replace(/\?/g, '\\?').replace(/\./g, '\\.')).join('|')

const regex = new RegExp(` ?(${str}) ?`, 'g')

const result = input.replace(regex, ' ^$1^ ').trim()

console.log(result)

Now the issue is if you have this input as the string:

this is ^,^ a text ^?^ ? you will get a repetition of ^ sign and we don't want this:

this is ^ ^,^ ^ a text ^ ^?^ ^ ^?^

Here is the desired result actually :

this is ^,^ a text ^?^ ^?^

CodePudding user response:

You can use

const signs = [',', '!!', '?!', '!?', '...', '..', '.', '?', '؟!', '!؟', '!', '؟', ':'];

const input = 'this is ^,^ a text ^?^ ?'

const str = signs.map(e => e.replace(/\?/g, '\\?').replace(/\./g, '\\.')).join('|')

const regex = new RegExp(`\\s*(?:\\^\\s*)*(${str})\\s*(?:\\^\\s*)*`, 'g')

const result = input.replace(regex, ' ^$1^ ').trim()

console.log(result)

Here, I added (?:\\^\\s*)* on both ends to match zero or more sequences of ^ and zero or more whitespaces, and replaced the literal space with \\s* to match any zero or more whitespaces.

Note that escaping is better done with the universal solution like in Is there a RegExp.escape function in JavaScript?:

const str = signs.map(e => e.replace(/[-\\^$* ?.()|[\]{}]/g, '\\$&')).join('|')
  • Related