0

I have a text message and I want to parse the special characters in it. I have the list of special characters. I wrote the following regex but this shows compile time error. Looks like there is something with escape characters, but i'm not able to figure out.

This is the character list, i want to replace, without the quotes "<3","<\/3",";p","C:","c:",":D",":-D",":/",":-/",":o",":-o",":p",":-p",":P",":-‌​P",":b",":-b",";-p",";b",";-b",";P",";-P","D:",":->",":>",":)",":-)","(:",";)",";‌​-)",":sj:","):",":(",":-(",":'(","=)","=-)",">:(",">:-(","8)",":\\\\",":-\\\\",":*",":-‌​*",":|",":-|"

return msg.replace(/(<3|<\/3|;p|C:|c:|:D|:-D|:/|:-/|:o|:-o|:p|:-p|:P|:-P|:b|:-b|;-p|;b|;-b|;P|;-P|D:|:->|:>|:)|:-)|(:|;)|;-)|:sj:|):|:(|:-(|:'(|=)|=-)|>:(|>:-(|8)|:\\\\|:-\\\\|:*|:-*|:||:-|)/g, function myFunction(x){
  console.log(x);
  return x;
}

Unexpected token (105:52) Unexpected token (105:52)

iamsaksham
  • 2,301
  • 4
  • 21
  • 42
  • is it the complete example code ? if not do share, and also paste the error / exception traceback – Nabeel Ahmed Jun 22 '16 at 07:13
  • 1
    No sense in fighting with escaping if you can do it more simply. Keep your special strings in an array, and build the regex dynamically using the `escapeRegExp` function found in [Escape string for use in Javascript regex](http://stackoverflow.com/a/6969486/6263819). You can easily map each special string with the `escapeRegExp` and then join all of the escaped strings with `.join("|")` to get a properly constructed regexp. It'll keep your list of strings in an easy to maintain state, in case you want to add more. – Michael Gaskill Jun 27 '16 at 03:42

1 Answers1

1

You haven't escaped special meta characters in your regex like (, ), / etc.

You can also shorten your regex substantially using character classes and optional matches.

I've reduced it to:

return msg.replace (
   /<\/?3|[cCD()]:|:-?[\/DopPb)>()|]|;-?[pbP)]|:-?\\\\|:sj:|:'\(|=-?\)|>:-?\(|8\)/g,
    function myFunction(x) {
       // ....
    }
)
iamsaksham
  • 2,301
  • 4
  • 21
  • 42
anubhava
  • 664,788
  • 59
  • 469
  • 547