Replace the last value separated by commas with another with regex

I have a line as follows:

var str = "a,b,c,a,e,f"; 

I need to replace the last element, separated by commas, with another.

ie, str = "a,b,c,a,e,anystring"; 

I did this with a method splitand added it to create a new line. But it does not work as expected

What I did 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?

+4
source share
2 answers

You can use with regex to match the last line replace() /,[^,]+$/

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);
Run code

Regular expression visualization


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);
Run code

split(), , join()

var str = "a,b,c,d,e,old";
var arr = str.split(',');
arr[arr.length - 1] = 'new';
var res = arr.join(',');
document.write(res);
+10

String.substring() 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'));
+2

Source: https://habr.com/ru/post/1616162/


All Articles