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?

4

3 回答 3

6

您需要使用反斜杠 (\)转义表达式中的 [ 和 ] 字符,如下所示:

        var msgtxt = gk_text.replace(/\[/g, '<');
        msgtxt     = msgtxt.replace(/\]/g, '>');
于 2012-11-16T20:41:52.610 回答
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, '>');
于 2012-11-16T20:38:59.733 回答
0

您需要转义[]字符\,因为 then在正则表达式中有特殊含义

var msgtxt = gk_text.replace(/\[/g, '<').replace(/\]/g, '>');
于 2012-11-16T21:12:42.477 回答