如果它包含相同的短语,如何替换确切的字符串?
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
。
答案 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:
}