skip to Main Content

since javascript doesn’t support look behinds, i had problem creating this regex.

I have a string {sadsada and I want to put an " after { if and only if { seems to exist to the left a random alphabet character (case insensitive)

and I want to do it for all occurences.

so basically, this {asdadafafafsa will turn into {"sadafsafa

I tried with

string.replace(/{.*/g, '{"')

but this also removes the alphabetic characters to the right. and i want to achieve this with one regex expression only without any before hand checks.

Thank you in advance

2

Answers


  1. console.log("{asdadafafafsa {jdslfds {123}}".replace(/{(D)([^{]*)/g, '{"$1$2'))
    
    {"asdadafafafsa {"jdslfds {123}}
    

    use w instead of D if you want to match digit as well

    https://www.w3schools.com/jsref/jsref_regexp_wordchar.asp

    Login or Signup to reply.
  2. "… since javascript doesn’t support look behinds, i had problem creating this regex. …"

    Yes it does.

    "… I have a string {sadsada and I want to put an " after { if and only if { seems to exist to the left a random alphabet character (case insensitive) …"

    You can match this index with the following pattern.

    (?<={)(?=[a-z]+)
    

    Here is an example.

    var s = '{sadsada'
    s = s.replace(/(?<={)(?=[a-zA-Z]+)/, '"')
    console.log(s)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search