0

I can't, for the life of me, figure out how to replace all [ with < and all ] with > in a value in JavaScript.

Here's what I've tried and it just doesn't work:

function SwitchDialog(NextDialog)
{
    if (NextDialog=='SCHEDULE') {
        $('.popup1').smart_modal_hide();
    } else if (NextDialog=='LICENSEE') {
        gotoLicensee(licenseeLink);
    } else if (NextDialog=='REVIEWCART') {
        window.location = CART_URL;
    } else if (NextDialog=='RFO') {
        window.location = REGISTER_FOR_OTHERS_URL;
    } else {
        if (NextDialog=='PREREG') {
            var msgtxt = gk_text.replace(//[/g, '<');
            msgtxt     = msgtxt.replace(//]/g, '>');
            DialogTemps[NextDialog].msgtext = msgtxt; // error occurs on this line
        }
        RenderDialog(NextDialog);
    }
}

I get a Syntax error: "missing ) after argument list at the ; on the line that assigns the msgtext.

What the heck am I doing wrong?

2
  • 2
    @Maccath: To do multiple replaces you need a global regex. Commented Nov 16, 2012 at 20:42
  • 1
    You're right, sorry, blonde moment. :P Commented Nov 16, 2012 at 20:47

3 Answers 3

6

You need to escape the [ and ] characters in your expression with a backslash (\), like so:

        var msgtxt = gk_text.replace(/\[/g, '<');
        msgtxt     = msgtxt.replace(/\]/g, '>');
Sign up to request clarification or add additional context in comments.

Comments

4

You commented out the closing ), hence the error.

You need to escape a / in a regex, and not a bad idea to escape the [ and ] as well, even though it's likely not needed here.

var msgtxt = gk_text.replace(/\/\[/g, '<');
msgtxt     = msgtxt.replace(/\/\]/g, '>');

4 Comments

It's a freaking regex expression
@MB34: "It's a freaking regex expression" Not when you make it a feaking code comment.
I stand corrected. I am not good at Regex, as evidenced by my attempt. I went to regex101.com and built it and it looks just like the one you posted and works correctly, thanks. I will accept once I'm able.
@MB34: If you didn't want to include the / character in the regex, then you should accept the other answer.
0

You need to escape [ and ] characters with \, as then have special meaning in regex.

var msgtxt = gk_text.replace(/\[/g, '<').replace(/\]/g, '>');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.