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

时间:2014-08-21 13:03:08

标签: javascript

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

2 个答案:

答案 0 :(得分:2)

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;

答案 1 :(得分:1)

使用replace功能:

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