2016-07-05 1 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(//gで、 ''); ' –

+0

なぜ'/the \ s/'を比較してみませんか?これは単語theとそれの後のスペースを比較します。 –

+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

/スペースは空白を含むかもしれないテキストのために働きません –

+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/

関連する問題