Solved

How to replace value in string delimited

Posted on 2012-03-14
1
187 Views
Last Modified: 2012-03-14
How would I replace the nth ( third value for example) in a string delimited  by colones?

one:two:three:four:five:six

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?

Thanks!
0
Comment
Question by:894359
1 Comment
 
LVL 18

Accepted Solution

by:
nap0leon earned 500 total points
ID: 37722214
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.

<script>
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(":")
document.write(newStr)
</script>

Open in new window

0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
ASP.NET gridview select textbox on focus 2 37
CSS: Making Pure CSS read more boxes thinner 5 31
Hide cell in a table 2 15
Call a function within the ASP code 4 12
Today I would like to talk about localizing (Internationalization) JavaScript applications. Introduction When creating an application that is going to be used by many people around the globe, it is important to remember that not everyone speak…
I've been trying to accomplish this for a while and it just struck me yesterday how to accomplish this task. I have done searches all over the internet looking for ways to email pages from my applications and finally I have done it!!! Every single s…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question