Solved

How to replace value in string delimited

Posted on 2012-03-14
1
193 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
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…
Suggested Courses

622 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