-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.

Preshan Pradeepa
  • 698
  • 14
  • 31
  • 1
    You need to show us what you've tried before we can tell you why it was wrong. – TankorSmash Sep 21 '15 at 20:24
  • not sure, but I thought I would leave this helpful tidbit here: http://regexr.com/ – Shockwave Sep 21 '15 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 – Rodrigo Gomes Sep 21 '15 at 20:25
  • Please refer to this link for some idea : http://stackoverflow.com/questions/3720012/regular-expression-to-split-string-and-number – Ruchi Sep 21 '15 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](https://developer.mozilla.org/en-US/) has helped me understand a lot of things, so I'd recommend that as a resource – Jabari King Sep 21 '15 at 20:37

1 Answers1

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) ? '' : ', ';
}
kecal909
  • 156
  • 2
  • 10
  • 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. – jfriend00 Sep 21 '15 at 20:34