0

I have this string in the form of

ItemName1:Rate1:Tax1_ItemName2:Rate2:Tax2:_ItemName3:Rate3:Tax3_ItemName4:Rate4:Tax4 (and so on, upto item 25).

What I have to do is, user will pass a index, (say 2) grab the item at that index, when this string is split by _, for eg. if index is 2, I would get the substring ItemName3:Rate3:Tax3. another thing the user will pass is 3 args, indicating newItem, newRate, and newTax, then I have to replace these old items found at that particular index with these new values and return the new string. Perhaps an example would make it clear

var itemList=ItemName1:Rate1:Tax1_ItemName2:Rate2:Tax2:_ItemName3:Rate3:Tax3_ItemName4:Rate4:Tax4

user passed arguments, 2, Denim Jeans, 399.00, 14.34.
This must replace the original itemList and return

ItemName1:Rate1:Tax1_ItemName2:Rate2:Tax2:_Denim Jeans:399.00:14.34_ItemName4:Rate4:Tax4

(Hope I made myself clear).
I know the simplest way would be first split the itemList by _ and then at given index, split by : and then replace those items, then using a for loop make a new string and then return that new string. But it seems like a lot of work. Isn't there a simple way that this could be achieved by using .each() and/or .map(), though may be inside a for, I won't mind that!

1 Answer 1

0

Do you mean something like this?

var items = str.split('_').map(function(v){ return v.split(':') });

That will generate an array:

[
  ["ItemName1","Rate1","Tax1"],
  ["ItemName2","Rate2","Tax2"],
  ["ItemName3","Rate3","Tax3"],
  ["ItemName4","Rate4","Tax4"]
]

Demo: http://jsfiddle.net/elclanrs/7uVDM/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.