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)

2
  • is it the complete example code ? if not do share, and also paste the error / exception traceback Commented Jun 22, 2016 at 7: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. 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. Commented Jun 27, 2016 at 3:42

1 Answer 1

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) { // .... } ) 
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for shortening it for me. Can you please explain how you shortened it for others who might read it.
Yes that's what I wrote in answer shorten your regex substantially using character classes and optional matches
Hey, shortening it makes weak, It satisfies as soon as i press :, but i want it to satisfy only when its :) like so. Maybe some edit can do it
its `:|'. Wait I'll share the list. I knw its confusing
<3 aint working. Checking for more
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.