+ 3

regexp :help

how replace this string : "number variable name ;" with this :"var variable name=0;" via regexp in js? first attempt: var code=` number ba; console.log (a) ; `; console.log (code.replace(/number \w{1,10}/g),"var variable name=0;" ); how detect variable name?

17th Apr 2021, 3:41 PM
Mehran
Mehran - avatar
6 Answers
+ 3
Did you not know, about showing first your attempt here?
17th Apr 2021, 4:17 PM
JaScript
JaScript - avatar
+ 3
Mehran The following should work: ---- const subject = "number variable name ;" const pattern = /^(.|\r?\n)*(number) (variable) (name)(.|\r?\n)*$/ig const replace = "var $3 $4=0;" console.log(subject.replace(pattern, replace)) ---- Outputs: var variable name=0; ---- NOTE: This part of the pattern "(.|\r?\n)*" is used to ignore other characters and line breaks that come before and after the line with the exact match you are looking for.
1st May 2021, 6:11 AM
David Carroll
David Carroll - avatar
+ 2
JaScript i edited my question.
17th Apr 2021, 4:48 PM
Mehran
Mehran - avatar
+ 2
David Carroll unfortunately, you misunderstood i want replace "int ab;" with this "var ab=0;" "ab" is variable name and may differ in another example.
1st May 2021, 4:12 PM
Mehran
Mehran - avatar
+ 2
Mehran You wrote, "unfortunately, you misunderstood..." Hmm... đŸ€” I suppose I did the best I could, given the ambiguous details provided in your question. 😉👌 I initially had questions about your example as it really didn't make sense to me. But, I figured you were still in the early stages of figuring out how text pattern matching works. It was also after 3am when I posted and decided not to explore the dozens of possibilities of what you probably meant to ask and just answered using your literal example. Hence... my "misunderstanding" as you put it. 😉 That said, your follow up example is now different from your earlier example. So... perhaps, all you need is: ---- const subject = "int ab ;" const pattern = /([a-z]+) ([a-z_\d]+).*/ig const replace = "$1 $2=0;" console.log(subject.replace(pattern, replace)) ---- Outputs: int ab=0; ---- NOTE: I'm not accounting for scenarios that aren't clearly stated, like line breaks and extra spaces and such. I'm only focusing on what you asked.
1st May 2021, 11:25 PM
David Carroll
David Carroll - avatar
+ 1
David Carroll thanks a lot.
2nd May 2021, 3:42 AM
Mehran
Mehran - avatar