Using javascript regex containing '@' in razor

痴心易碎 提交于 2019-12-17 19:34:07

问题


I am performing email address validation with javascript in a razor view page. The regex I am going to use is similar to the one proposed at Validate email address in JavaScript?

However, because the regex contains an '@' character, I am getting parser error when try to run the web app.

my regex looks like

/^...otherpart @* ... other part$/

I tried to add an '@' character to make the in the origin regex ... @@* ..., this eliminated the compilation error but seems to make the regex stops working. (we have used it in another web app that does not use razor engine, so I know it works).

Is there any other way to escape the '@' character?


回答1:


You can add another @ in front of it to escape @@, try leaving out the quantifer *. If this doesn't seem to work then add <text></text> around the function, it tells Razor to not parse the contents. Alternatively you can put Javascript in a separate file to accomplish your needs.

If for some reason you have multiple @@ in your string, place code blocks ahead @:@@




回答2:


Put the following inside the regEx instead of @:

@('@')

The above will be rendered to a single @.

Your example will become:

/^...otherpart @('@')* ... other part$/



回答3:


Simply just use double @@.
It works for me and I think that is the only way.



来源:https://stackoverflow.com/questions/19440990/using-javascript-regex-containing-in-razor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!