Hi!

I am looking for a function that will replace last occurence of a substring from a string:

tmpStr: xxx, yyy, zzz, sss,
The desired outcome: xxx, yyy, zzz and sss
(ie: remove last letter and then replace last occurrence of ",")

The string can differ,
* xxx,
* xxx, yyy,
* xxx, yyy, zzz,

Do anyone of you have a neat fuction for that? I will be so happy for all input!! ;)Thanks in advance!

Member Avatar for Pnorq
var str = "xxx, yyy, zzz, sss,";
if(  str.indexOf( "," ) > 0 && str.indexOf( "," ) != str.lastIndexOf( "," )  ) { // tests for >1 character group in string
   str = str.slice( 0, str.lastIndexOf( "," ) ); // lops off the last comma
   str = str.slice( 0, str.lastIndexOf( "," ) ) + " and "  + str.substring( str.lastIndexOf( "," )+1 );
}
// str now is: "xxx, yyy, zzz and sss";

@Pnorq
Your function is correct, but there are a lot going on. :)

@kalleanka
Use regular expression and replace() function.

var str = "xxx, yyy, zzz, sss,";
str = str.replace(/,\s*(\w+),\s*$/, "and $1")  // Done! Case for any more than 1 -> xxx, yyy,
str = str.replace(/,\s*$/, "")  // Done! Case for only 1 appear -> xxx, (won't interfere with the case 1)

split() method can do it directly. check this function.

Member Avatar for Pnorq

Your function is correct, but there are a lot going on. :)

And there's a reason for that. From the context of the OP's post, they clearly aren't familiar with JavaScript or perhaps programming methodologies (probably both). Rather than confusing them with a powerful yet confusing (for a beginner) regex expression, I wanted to give them a solution that is more easily understood at their current level of competency in Javascript.

My hope is by providing verbose (coding-wise) and simple answers, the OPs here will actually learn what the solutions do rather than copy some apparent gibberish that works, and move on to their next programming task without really understanding what's going on.

So yes, if it was me writing production code in one of my systems, I'd go straight to a regex solution, but if the OP wants a production-level black box, I'll be happy to provide my PayPal account and they can remunerate me for my time! :D

Member Avatar for Pnorq

split() method can do it directly. check this function.

split() won't put in the " and " however.

Hey Pnorg,

Of course split() will not put 'and', I just ask to explore this method. But your code is not working even in non "production-level" :P. The second line after if-condition is destroying the original string.

And, never presume that simplicity in code is more important than good and working code. When it comes to string manipulation regEx is the best practice rather than using too many string functions to do same job.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.