Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.RegexMail.

I can’t modify the value of @Params.RegexMail beforehand.

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 /(.*)/
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading