Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace last comma separated value by another using regex

I have a string as follows :

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

What I need is replace the last comma 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?

like image 591
Santhucool Avatar asked Dec 14 '22 10:12

Santhucool


2 Answers

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

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

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);
like image 86
Pranav C Balan Avatar answered Dec 17 '22 01:12

Pranav C Balan


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'));
like image 36
StackSlave Avatar answered Dec 17 '22 01:12

StackSlave