2

I would love to use the String.replace() function in JavaScript to replace a certain portion of a first string with some non deterministic user input (second string)

Example 1:

> var userinput = "^fancy $& regexlike stuff $/i"
> "some @@include test".replace(/@@include/, userinput)
"some ^fancy @@include regexlike stuff $/i test"

should be

> var userinput = "^fancy $& regexlike stuff $/i"
> "some @@include test".replace(/@@include/, userinput)
 "some ^fancy $& regexlike stuff $/i test"

Example 2:

> var userinput = "^fancy $& regexlike stuff $/i"
> "some @@include test".replace(/@@include/, userinput)
 "some ^fancy & test"

should be

> var userinput = "^fancy &$ regexlike stuff $/i"
> "some @@include test".replace(/@@include/, userinput)
 "some ^fancy &$ regexlike stuff $/i test"

So here is the actual question:

How do I tell String.replace() to ignore all regex syntax given in its second argument userinput? Is there any sanatize flag or so?

Thank you verymuch in advance!

3
  • simply escape it with back slash to consider it as a character... Commented Feb 14, 2018 at 6:53
  • well.. but I would need the user to do that or to feed the input through a custom sanatize() function first.. already thought of that, but it seems uncomfortable compared to a "isSanatized" flag on replace() Commented Feb 14, 2018 at 6:55
  • Have a look at stackoverflow.com/a/2593661/8767753 Commented Feb 14, 2018 at 7:00

1 Answer 1

2

Just use the function syntax of the String#replace. The string returned from the function is considered as a string. Special characters in the string are not considered as meta-characters.

var userinput = "^fancy $& regexlike stuff $/i";
var output = "some @@include test".replace(/@@include/, () => userinput);
console.log(output);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.