Solved

How to replace value in string delimited

Posted on 2012-03-14
1
188 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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
VBScript on Html 15 48
binding event to form in window.open 9 42
Can anyone see what is the fault in my javascript code? 8 33
send email part1 9 28
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…
In this article, we'll look how to sort an Array in JavaScript, including the more advanced techniques of sorting a collection of records either ascending or descending on two or more fields. Basic Sorting of Arrays First, let's look at the …
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…

821 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