1

hey guys just a quick one for tonight.

i just want to change a smiley face e.g :-P to a html code like <span class=surp></span> but it comes out with a error which is
Uncaught SyntaxError: Invalid regular expression: /:-(/: Unterminated group


this is part of my code

newmessage = newmessage.replace(/:-(/gi, "<span class=sad></span>"); 

i figured it out and it doesn't like the bracket so is there any other way to do this with the bracket?

2 Answers 2

3

In a regular expression, ( begins a group - but in your case you want to match the literal (, so you need to escapg it with a backslash:

newmessage = newmessage.replace(/:-\(/gi, "<span class=sad></span>"); 

Besides that, I would make the - optional - most people use :( instead of :-(:

newmessage = newmessage.replace(/:-?\(/gi, "<span class=sad></span>"); 
Sign up to request clarification or add additional context in comments.

Comments

0

As correctly stated by @ThiefMaster, you need to escape a bracket to use it literally in a regular expression, using the escape character \.

But for what you want to do, I think you would be best passing a function as the second argument, so you can replace everything in a single .replace() call with a single regex that matches all smileys you want to replace.

Something like this:

newmessage = newmessage.replace(/(:-\(|:\(|:-\)|:\)|:-P|:P)/gi, function(match) { switch (match.toUpperCase()) { case ':-)': case ':)': return '<span class="happy"></span>'; case ':-(': case ':(': return '<span class="sad"></span>'; case ':-P': case ':P': return '<span class="surp"></span>'; default: return match; } }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.