-1

One word needs to be replace in long string:

var str=<long string>;
var newValue = "`" + <input from user> + "`";
var regexValue = new RegExp(oldValue, 'g');
str = str.replace(regexValue, newValue);

How is the best way to handle special characters? I have an input field in HTML which I can assign some regex.

Current problem,

When the new value is "table_?" the regex fails after that. This is just one case but there are other special characters which need to be handled. There is no other restriction on the input field.

batmaniac7
  • 422
  • 5
  • 17
  • 1
    Are you asking how to make a string that looks like a regex not be treated as such? -> [Escape string for use in Javascript regex](http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex) – Alex K. Feb 23 '15 at 20:02
  • 3
    You never pass `table_?` into the regex constructor, you're passing something called `oldValue` whatever that is, `table_?` is passed as a string to `replace` as the value to add as a replacement, as such the question doesn't really make sense – adeneo Feb 23 '15 at 20:05

1 Answers1

0

You can replace all special characters with the same, prefixed with a backslash to escape them. This is a very liberal replace, it escapes everything that's not whitespace or alphanumeric. You could be more strict by putting the specific characters in the character class, just remember to escape them (ala [\?\.]).

    nstring = "table_?"
    xstring = nstring.replace(/([^\s\w])/g,"\\$1");
    alert("Start string: " + nstring + "; end: " + xstring);

xstring then contains an escape-friendly string.

Regular Jo
  • 5,190
  • 3
  • 25
  • 47