我使用API獲取字符串的列表。例如:如何使用javascript從字符串中刪除第一個字「the」
'The Lord of the Rings: The Fellowship of the Ring 2001'
'The Lord of the Rings: The Two Towers 2002'
'The Lord of the Rings: The Return of the King 2003'
我想把它轉換成這樣:
'Lord of the Rings: The Fellowship of the Ring 2001'
'Lord of the Rings: The Two Towers 2002'
'Lord of the Rings: The Return of the King 2003'
不知怎的,我做到了通過使用下面的腳本,但有一些錯誤。請參閱test1和test2。
function myFunction(str) {
var position = str.search(/the/i);
if (position == 0) {
var str = str.substring(str.indexOf(" ") + 1, str.length);
}
return str;
}
TEST1:
str = "The Lord of the Rings: The Fellowship of the Ring 2001"
結果:
return = "Lord of the Rings: The Fellowship of the Ring 2001" // that's what i want
TEST2:
str = "There Will Be Blood 2007"
結果:
returns = 'Will Be Blood' // that's what i don't want
我只想從字符串中刪除第一個單詞「The」。
用途:'str.replace(/的/克, '');' –
爲什麼不用'/ the \ s /'來代替。這將比較單詞和後面的空格。 –
簡單地添加空格將不會工作,因爲空間可以是任何空格字符 –