使用正则表达式替换所有出现的字符串

时间:2014-07-01 09:54:48

标签: regex

嗨我想在所有情况下用shanmugam替换[[$ Title]]。这是我的代码。

    <script>
    emailContents = '[[FirstName]] [[LastName]] watched "AccelaCast Program" and sent you the following comment and link:[[iaf_message/5]][[#if iaf_message/6 No]]http://webcasts.advanstar.com/acc/iaf/1/[[$PROGRAMID]]/Clicking the URL above will take you to the webcast: "[[$Title]]" [[#else]]http://webcasts.advanstar.com/acc/iaf/1/[[$PROGRAMID]]/?_IAFSegment=[[$SEGMENT]]&_IAFTime=[[$posmmss]]Clicking the URL above will take you to the webcast "[[$Title]]" at the point in the program that [[/User/FirstName]] thought would be most relevant to you.[[#endif]]Message from Advanstar Communications[Sender IP: [[$IP]]] If you believe you have received this email in error, or for customer service at Accela Communications, please send a message to mailto:support.getinfoadvanstar.com Macros program id:    [[$programid]] pos: [[$pos]] segment: [[$segment]] pos minutes sec: [[$posmmss]] Title: [[$title]] ip: [[$ip]] link: [[#link http://getinfo2.advanstar.com/ASP/main.jsp Getinfo  Getinfo]] Image: [[#img http://getinfo2.advanstar.com/ASP/images/AdvanstarProgram175x37.jpg]] Eval#eval #3.2 floor :[[#eval #3.2 floor ]]'
    emailContents = emailContents.replace(/\[\[$Title\]\]/g,'shanmugam');
    console.log(emailContents);
</script>

请帮助我。

1 个答案:

答案 0 :(得分:2)

下面的代码会将[[FIRSTNAME]]替换为shanmugam,

emailContents = emailContents.replace(/\[\[FirstName\]\]/g,'shanmugam');

在正则表达式[]中是特殊字符(表示字符类),为了表示文字[]符号,您需要将其转义。

如果您想要不区分大小写替换$Title,请运行以下内容,

emailContents = emailContents.replace(/\[\[\$Title\]\]/gi,'shanmugam');
正则表达式中的

$具有特殊含义(表示一行的结尾)。要表示文字$,您需要将其转义。