2016-07-05 57 views
0

我使用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」。

+0

用途:'str.replace(/的/克, '');' –

+0

爲什麼不用'/ the \ s /'來代替。這將比較單詞和後面的空格。 –

+0

簡單地添加空格將不會工作,因爲空間可以是任何空格字符 –

回答

2

您可以使用正則表達式來實現這一目標。具體爲/^The\s/i。請注意,^非常重要,因爲它確保匹配只發現The的前導實例。

var arr = ['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']; 
 

 
var re = /^The\s/i; 
 
for (var i = 0; i < arr.length; i++) { 
 
    arr[i] = arr[i].replace(re, ''); 
 
} 
 

 
console.log(arr);

0

只需添加一個空格:

function myFunction(str) { 
 
    var position = str.search(/the\s/i); 
 
    if(position == 0){ 
 
    var str = str.substring(str.indexOf(" ") + 1, str.length); 
 
    } 
 
    return str; 
 
} 
 

 
console.log(myFunction("The Ring of Lords: The ring of Lords")); 
 
console.log(myFunction("There Ring of Lords: The ring of Lords"));

+0

/the /不會爲可能包含空格的文本工作,而不是空格 –

+0

建議使用'/ the \ s + /'替代。 –

+0

好的,作爲一個建議我編輯它 –

-1

只需使用此

var string = "The Lord of the Rings: The Fellowship of the Ring 2001"; 
var result = string.replace(/^The\s/i, " "); 
alert(result); 
0

您可以用SUBSTR功能做到這一點:

for(var i = 0; i < list.length; ++i){ 
    if(list[i].substr(0, 4).toLowerCase() == "the ") 
     list[i] = list[i].substr(4, list[i].length); 
} 

這裏是一個的jsfiddle:https://jsfiddle.net/pk4fjwyf/

相關問題