1

I have this text 'I'm Cristian'.

I'm using a regex to wrap every character in a different span element. I want to exclude the word Cristian from the operation I tried with Negative lookahead but i can't put it to work .

the basic regex is this

/([^\x00-\x40]|\w|\S)/g

i tried with

/(?!Cristian)([^\x00-\x40]|\w|\S)/g

but it doesn't work thanks for the help

cri_pava
  • 170
  • 11

1 Answers1

2

Use the following approach:

const string = `I'm Cristian`
console.log(string.replace(/\bCristian\b|([^\x00-\x40]|\w|\S)/g, 
     (match, group) => group == undefined ? match : `<span>${match}</span>`))
  1. Add the \bCristian\b pattern to the expression before a pipe
  2. Find out if your previous captured pattern was found
  3. If the previous is true, wrap the match with span, else, return the found text.
Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37
  • Thank youuuu. That worked. If you have time could you please explain why "?!" didn't work but "\b" did?? thanks. Really appreciated – cri_pava Feb 09 '21 at 23:31
  • 1
    @cri_pava `([^\x00-\x40]|\w|\S)` matches single character, and `(?!Cristian)` in front of that pattern cancels a match of that single character, but not a whole word like `Cristian`. – Ryszard Czech Feb 09 '21 at 23:33
  • alright . i see now . Thanks , If you have time I have another question; if i have a span element inside an h1 element and i want to exclude the span element from the selection with a regex , there is a way to do so ? – cri_pava Feb 09 '21 at 23:38
  • 1
    @cri_pava That does not sound like a good idea, but `/(?<=

    (?:(?!<\/?h1>).)*?)[^<]*<\/span>|\bCristian\b|([^\x00-\x40]|\w|\S)/gs` might work.

    – Ryszard Czech Feb 10 '21 at 00:07
  • thanks . I see that is not a really good practice , but if i don't find a better solution i will need to use this . Thanks for all the help . appreciated – cri_pava Feb 10 '21 at 15:39