-9

Here's the string:

var myString = "apple, 0.90, pear, 1.23, orange, 1.90";

What regular expression do I use to change the string to this:

apple: 0.90, pear: 1.23, orange: 1.90

I want to replace the comma after the end of the fruit to a colon.

5
  • 1
    You need to show us what you've tried before we can tell you why it was wrong. Commented Sep 21, 2015 at 20:24
  • not sure, but I thought I would leave this helpful tidbit here: regexr.com Commented Sep 21, 2015 at 20:24
  • 2
    please, post here some regex code you have tried and not working. Normally this community use to teach to fish, instead of give the fish Commented Sep 21, 2015 at 20:25
  • Please refer to this link for some idea : stackoverflow.com/questions/3720012/… Commented Sep 21, 2015 at 20:26
  • You should be more resourceful. I gave you an answer and also a second option to show that there's multiple ways to do things. Learn how to not give up so quickly. The javascript MDN has helped me understand a lot of things, so I'd recommend that as a resource Commented Sep 21, 2015 at 20:37

1 Answer 1

0

You can split the string into an array and then make new string. Like this:

var myString = "apple, 0.90, pear, 1.23, orange, 1.90";

var array = myString.split(', ');
var output = '';
for (var i = 0; i < array.length; i += 2) {
    output += array[i] + ': ' + array[i + 1];
    output += (i - 2 == array.length) ? '' : ', ';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Eeek no. A one line of simple .replace() will entirely solve this problem, but we are encouraging the OP to try for themselves before handing them a solution.

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.