admin 管理员组文章数量: 1086019
I have a string as follows :
var str = "a,b,c,a,e,f";
What I need is replace the last ma separated element by another.
ie, str = "a,b,c,a,e,anystring";
I have done it using split
method and adding it to make a new string. But it is not working as expected
What I done as follows :
var str = "a,b,c,d,e,f";
var arr = str.split(',');
var res = str.replace(arr[5], "z");
alert(res);
Is there any regex to help?
I have a string as follows :
var str = "a,b,c,a,e,f";
What I need is replace the last ma separated element by another.
ie, str = "a,b,c,a,e,anystring";
I have done it using split
method and adding it to make a new string. But it is not working as expected
What I done as follows :
var str = "a,b,c,d,e,f";
var arr = str.split(',');
var res = str.replace(arr[5], "z");
alert(res);
Is there any regex to help?
Share Improve this question edited Nov 17, 2015 at 7:18 Pranav C Balan 115k25 gold badges171 silver badges195 bronze badges asked Nov 17, 2015 at 7:12 SanthucoolSanthucool 1,7262 gold badges39 silver badges92 bronze badges2 Answers
Reset to default 10You can use replace()
with regex /,[^,]+$/
to match the last string
var str = "a,b,c,d,e,old";
var res = str.replace(/,[^,]+$/, ",new");
// or you can just use
// var res = str.replace(/[^,]+$/, "new");
document.write(res);
Or you can just use regex
str.replace(/[^,]+$/, "new");
var str = "a,b,c,d,e,old";
var res = str.replace(/[^,]+$/, "new");
document.write(res);
Or using split()
, replace the last array value with new string and then join it again using join()
method
var str = "a,b,c,d,e,old";
var arr = str.split(',');
arr[arr.length - 1] = 'new';
var res = arr.join(',');
document.write(res);
You could just use a String.substring()
of String.lastIndexOf()
:
function replaceStartingAtLastComma(str, rep){
return str.substring(0, (str.lastIndexOf(',')+1))+rep;
}
console.log(replaceStartingAtLastComma('a,b,c,d,e,f', 'Now this is f'));
本文标签: javascriptReplace last comma separated value by another using regexStack Overflow
版权声明:本文标题:javascript - Replace last comma separated value by another using regex - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744096377a2532973.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论