我使用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;
}
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
我只想删除第一个字""来自字符串。
答案 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);
答案 1 :(得分: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"));
&#13;
答案 2 :(得分: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/
答案 3 :(得分:-1)
只需使用此
var string = "The Lord of the Rings: The Fellowship of the Ring 2001";
var result = string.replace(/^The\s/i, " ");
alert(result);