Search code examples
regexasp.net-mvc-3escaping

Razor view escape @ sign in regular expression


IN MVC Razor view i am writing a regular expression to detect URL in text. Expression is

var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

But MVC is showing error on each @ sign , how can i escape to avoid error ?


Solution

  • You can use @@ to escape @

    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@@#\/%?=~_|!:,.;]*[-A-Z0-9+&@@#\/%=~_|])/ig;
    

    The html output will contain single @:

    <script type="text/javascript">
            var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    </script>