Joe*_*Joe 39
使用RegExp
和^
确保它是前缀,而不仅仅是字符串中的某个位置:
var arr = ['a1', 'a2', 'a54a'];
for(var i = 0, len = arr.length; i < len; i++) {
arr[i] = arr[i].replace(/^a/, '');
}
arr; // '1,2,54a' removing the 'a' at the begining
Run Code Online (Sandbox Code Playgroud)
Way*_*ett 12
已经给出的许多答案都是错误的,因为它们会从每个元素中的任何位置(不仅仅是开头)中删除目标字符串.这是另一种方法:
var str = "str_";
["str_one", "str_two_str_", "str_three"].map(function(el) {
return el.replace(new RegExp("^" + str), '');
});
Run Code Online (Sandbox Code Playgroud)
结果:
["one", "two_str_", "three"]
Run Code Online (Sandbox Code Playgroud)
或者,如果您更喜欢简单迭代(没有高阶函数):
var str = "str_";
var list = ["str_one", "str_two_str_", "str_three"];
for (var i = 0; i < list.length; i++)
list[i] = list[i].replace(new RegExp("^" + str), '');
Run Code Online (Sandbox Code Playgroud)
AJc*_*dez 10
function trimPrefix(str, prefix) {
if (str.startsWith(prefix)) {
return str.slice(prefix.length)
} else {
return str
}
}
var prefix = "DynamicPrefix"
trimPrefix("DynamicPrefix other content", prefix)
Run Code Online (Sandbox Code Playgroud)
小智 8
var pre = 'prefix_';
my_arr = my_arr.map(function(v){ return v.slice(pre.length); });
Run Code Online (Sandbox Code Playgroud)
如果需要完整的浏览器支持,请参阅MDN.map()
.
.forEach()
如果需要保留原始数组,也可以使用.
var pre = 'prefix_';
my_arr.forEach(function(v,i){ my_arr[i] = v.slice(pre.length); });
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
31097 次 |
最近记录: |