We help IT Professionals succeed at work.

Replace white space with comma

lulu50
lulu50 asked
on
Hi,

I have a textarea where I want the system to replace all the white spaces with a comma.

my code works if I hit the break between each input but if I have my text without hitting the break between each text
it will not replace the white spaces with a comma.

this is what I have:


           var str = $('#ItemList').val();

            str = $('#ItemList').val().replace(/(?:\r\n|\r|\n)/g, ',');
           
            var partsOfStr = str.split(', ');
       
            $('#ItemList').val(partsOfStr);

Open in new window


 Thank you for your help

Lulu
Comment
Watch Question

Eduard GherguArchitect - Coder - Mentor

Commented:

Hi,

What about

str.replace( /  +/g, ' ' );

Commented:

Add |\s to your pattern:

(?:\r\n|\r|\n|\s)

leakim971Multitechnician
Top Expert 2014

Commented:
you must set the number of columns of your textarea :  cols="21"
or any other number but it need to match with the number in the code

test page : https://jsfiddle.net/xg5Lstvu/

var textareaValue = $("#ItemList").val();
var numberOfTextareaChar = textareaValue.length;
var numberOfCharPerRow = 21;
var numberOfRow = parseInt(numberOfTextareaChar/numberOfCharPerRow);
var partsOfStr = [];
for(var i=0;i<numberOfTextareaChar;i+=numberOfCharPerRow) {
	partsOfStr.push(textareaValue.substring(i, i+numberOfCharPerRow));
}
partsOfStr = partsOfStr.join(", ")
// CHECKING :
alert(partsOfStr);

Open in new window

Most Valuable Expert 2011
Top Expert 2015

Commented:
Add |\s to your pattern:

(?:\r\n|\r|\n|\s)
While I agree that this is the answer, it's redundant:  \s includes \r and \n. A simple:

.replace(/\s+/g, ',')

Open in new window


should suffice.
lulu50Web application

Author

Commented:
gr8gonzo,

I added |\s to my pattern and it worked great!!!!

I want to thank you all for your help.

gr8gonzo you are the pro today!!!!

Thank you  gr8gonzo!!!!!