JS替换使用相同的短语

时间:2018-05-24 06:10:54

标签: javascript

如果它包含相同的短语,如何替换确切的字符串?

var campaign = "sub.site.com";
campaign = campaign.replace("site.com", "campaign 1");
campaign = campaign.replace("sub.site.com", "campaign 2");
output = [{campaign: campaign}];

在这种情况下,输出为sub.campaign 1。我希望它是campaign 2

1 个答案:

答案 0 :(得分:0)

var campaign = "sub.site.com";
campaign = campaign.replace("site.com", "campaign 1");// campaign = 'sub.campaign 1'
campaign = campaign.replace("sub.site.com", "campaign 2"); //there is no instance of 'sub.site.com' in 'sub.campaign 1'
output = [{campaign: campaign}];

您正在替换site.com中的sub.site.com位,因此它与

不匹配

更清洁的方式

var campaign = "sub.site.com";
if(campaign === 'site.com') {
   output = [{campaign: 'campaign 1'}];
}
else if(campaign === 'sub.site.com') {
   output = [{campaign: 'campaign 2'}];
}

switch("sub.site.com"){
  case 'site.com':
    output = [{campaign: 'campaign 1'}];
    break;
  case 'sub.site.com':
    output = [{campaign: 'campaign 2'}];
    break;
  default:      
}