繁体   English   中英

如何使用JavaScript从字符串中删除第一个单词“ the”

[英]How to remove first word “the” from string using javascript

我使用API​​获取字符串列表。 例如:

'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;
}

测试1:

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

测试2:

str = "There Will Be Blood 2007"

结果:

returns = 'Will Be Blood' // that's what i don't want

我只想从字符串中删除第一个单词“ The”。

您可以使用正则表达式来实现此目的。 特别是/^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); 

只需添加一个空格:

 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")); 

您可以使用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/

只需使用此

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM