Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing commas in resultset with new line in jQuery

I have not had to do something like this in the past and am wondering if it is indeed possible. I am allowing multiple code numbers to be added in an so long as they are delimited by commas. What I am wanting to do is upon the user clicking on the "okay" button that a showing the numbers entered will show them one on top of each other with a "delete" button next to them. That part is easy...the hard part is getting the comma stripped out and the new line placed in its stead.

Are there any examples or samples that anyone can point me too?

like image 641
Amidude Avatar asked Jun 13 '12 15:06

Amidude


1 Answers

You'd use String#replace with a regular expression using the g flag ("global") for the "search" part, and a replacement string of your choosing (from your question, I'm not sure whether you want <br> — e.g., an HTML line break — or \n which really is a newline [but remember newlines are treated like spaces in HTML]). E.g.:

var numbers = "1,2,3,4,5,6";
numbers = numbers.replace(/,/g, '<br>'); // Or \n, depending on your needs

Or if you want to allow for spaces, you'd put optional spaces either side of the comma in the regex:

var numbers = "1,2,3,4,5,6";
numbers = numbers.replace(/ *, */g, '<br>'); // Or \n, depending on your needs
like image 59
T.J. Crowder Avatar answered Sep 21 '22 01:09

T.J. Crowder