在JavaScript中,我如何删除字符串的某些部分

In JavaScript how do I remove certain part of a string?

本文关键字:字符串 删除 些部 JavaScript 何删除      更新时间:2023-09-26

我需要在一个短语后分割字符串,例如id字符串是"Stay in London",我需要删除"Stay in",我知道这必须很简单,但我发现很难找到一种方法来做到这一点

var str = "Stay in London",
//Here's a few ways, but there are many more 
//and it all depends how dynamic it needs to be...
london = str.split(' ').pop(),
london = str.match(/'b('w+)$/)[0],
london = str.slice(8),
london = str.replace('Stay in ', ''),
//and we could get silly... ;)
london = [].filter.call(str, function (letter, index) {
    return index >= 8;
}).join(''),
london = str.split(' ').reduce(function (r, token) {
    if (r.tokensToExclude.indexOf(token) == -1) r.finalString += token;
    return r;
}, { tokensToExclude: ['Stay', 'in', ' '], finalString: '' }).finalString;

使用replace函数:

"Stay in London".replace("Stay in ", "");