We help IT Professionals succeed at work.

How to replace value in string delimited

894359 asked
How would I replace the nth ( third value for example) in a string delimited  by colones?


and I want third segment ("three" in this case) to "apple". What's the best way to do this for any position in this string?

Watch Question

Top Expert 2011
I'm sure you could do it in a regex that might be more effiecient, but I suck at regex, so my approach would be to split the string into an array and replace the nth item in the array, then recombine the elements back into a string.

var str = "one:two:three:four:five:six"
var arrayStr = str.split(":");

var n = 3;  //the position of the item you want to replace
var newItem="apple"; //the value you want to go into the nth position

arrayStr[n-1] = newItem; //using n-1 because arrays start at 0, not 1

var newStr = arrayStr.join(":")

Open in new window

Explore More ContentExplore courses, solutions, and other research materials related to this topic.