+ 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?
6 Answers
+ 3
Did you not know, about showing first your attempt here?
+ 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.
+ 2
JaScript i edited my question.
+ 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.
+ 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.
+ 1
David Carroll thanks a lot.