带有变量的javascript正则表达式

时间:2016-12-08 11:24:29

标签: javascript regex

如何定义正则表达式变量,例如在将html链接标记转换为角度链接标记的情况下:

<a href="/myapp/home">Home</a>
<a href="/myapp/about">About</a>
... many others can include more a, html, divs, tables etc

<a [routerLink]="['/home']">Home</a>
<a [routerLink]="['/about']">About</a>
... without change

这似乎很容易,但最重要的是名字&#34; home&#34; &#34;约&#34;是动态的,所以我需要将它们定义为任何变量,如:

<a{ANYTHING as $1}href="/myapp/{ANYTHING as $2}"

<a $1 [routerLink]="['$2']"

1 个答案:

答案 0 :(得分:1)

我真的不确定正则表达式是最好的方法,但这是一个例子:

str = '<a some content 1 href="/myapp/home" some other content 2>Home</a>'
regex = /<a(.*)href="\/myapp(\/[^"]*)"(.*)>(.*)<\/a>/
if (regex.test(str)) {
  t = regex.exec(str)
  new_str = '<a' + t[1] + '[routerLink]=\"[\''+t[2] +'\']\"'+t[3]+'>'+t[4]+'</a>'
  console.log(str)
  console.log(new_str)
}