Solved

How to replace value in string delimited

Posted on 2012-03-14
1
183 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
Comment Utility
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 Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
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…

762 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now