Reputation: 11045
This is driving me crazy. I have a PHP script that gets some data from MySQL and saves it as a string with elements separated by commas.
A JavaScript takes that string and replace the commas by '\n' and displays it inside a text area. Now, I can add new lines to the text from the text area. When clicking on a button, the string should be converted back to elements separated by commas, then set to the PHP (through AJAX) again, to be saved. The problem is with the JavaScript, that cannot detect the '\n' character when there are more than 3 lines in the text-area.
// These are the lines of the text-area, after replacing ',' by '\n'
var textarealines=input_hidden_element.value.replace(',','\n').replace(',','\n');
// When trying to replace '\n' by ',' and send back, PROBLEM!
var AjaxRequest = WT.AjaxObject();
AjaxRequest.open('POST', WT.AjaxLocation, true);
AjaxRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
AjaxRequest.send('values=' + textarealines.replace('\n', ',').replace('\n', ','));
AjaxRequest.onreadystatechange = function() {
// Bla bla bla
}
So, what am I doing wrong? Up to two lines the new lines are correctly replaced by commas but when I add more than 2 lines only the first 2 are replaced, next lines are sent with the 'n' character, as a single line of text containing '\n'. Thanks
Upvotes: 2
Views: 4491
Reputation: 6665
Try adding the global search flag:
textarealines.replace(/\n/g, ',')
Note that the /\n/g
is not in single quotes, meaning that it's a regular expression.
Similarly, to go from line feeds to commas, try:
input_hidden_element.value.replace(/,/g, '\n')
This question is similar to "How to replace all points in a string in JavaScript."
Upvotes: 3