skip to Main Content

I’m working on a project where this string ^[email protected]$ is stored in a parameter.
It’s possible to retrieve it in the JS part using @Params.RegexMail.

I can’t modify the value of @Params.RegexMail 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 ^[email protected]$.

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 ?

2

Answers


  1. If you’re not seeing any slashes when you log the string containing the regular expression directly to the console, it suggests that the slashes are being removed or interpreted in a different way before they reach the console. This might be due to how the framework or environment you’re working in processes strings.

    In this case try to use
    console.log(String.raw(filtreEmail));

    Login or Signup to reply.
  2. 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 /^[email protected]$/ or /(.*)/
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search