Avatar of lulu50
lulu50
Flag for United States of America asked on

Replace white space with comma

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
C#JavaScriptjQueryJSON

Avatar of undefined
Last Comment
lulu50

8/22/2022 - Mon
Eduard Ghergu

Hi,

What about

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

ASKER CERTIFIED SOLUTION
gr8gonzo

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
leakim971

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

kaufmed

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.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
lulu50

ASKER
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!!!!!