ryanc1256
ryanc1256

Reputation: 570

javascript string replacement

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?

Upvotes: 1

Views: 133

Answers (2)

DaveRandom
DaveRandom

Reputation: 88647

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;
  }
});

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318468

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>");

Upvotes: 3

Related Questions