Search code examples
javascriptstringrazor

How to keep a single backslash in JavaScript?


I'm working on a project where this string ^\S+@demo\.com$ is stored in a parameter. It's possible to retrieve it in the JS part using @Params.FiltreEmail.

I can't modify the value of @Params.FiltreEmail beforehand.

I tried to do console.log("@Html.Raw(@Params.FiltreEmail)"); and even

var x = "@Html.Raw(@Params.FiltreEmail)".replace("\\", "\\\\"); 
console.log(x);

but both ways ended up by returning ^S+@demo.com$.

My goal is to be able to define the following regex:

var exp = ("@Html.Raw(@Params.FiltreEmail)" !== "") ? "@Html.Raw(@Params.FiltreEmail)" : "(.*)";
var regex = new RegExp(exp);

How can I achieve this ?


Solution

  • The .replace("\\", "\\\\") would only replace the FIRST set, but they would already have been lost when declared.

    Instead use server side JSON encode:

    // @using System.Web.Helpers
    
    let escapedRegex = `^\\S+@demo\\.com$` // "@Html.Raw(Json.Encode(Params.FiltreEmail))"; // Server-side rendering happens here
    
    console.log(escapedRegex); // Check if the escaping is done right
    
    let exp = escapedRegex? escapedRegex : "(.*)";
    let regex = new RegExp(exp);
    console.log(regex); // This should now show /^\S+@demo\.com$/ or /(.*)/