I have a text in a textarea and I read it out using the .value attribute.
Now I would like to remove all linebreaks (the character that is produced when you press Enter) from my text now using .replace with a regular expression, but how do I indicate a linebreak in a regex?
If that is not possible, is there another way?
How you'd find a line break varies between operating system encodings. Windows would be \r\n, but Linux just uses \n and Apple uses \r.
I found this in JavaScript line breaks:
someText = someText.replace(/(\r\n|\n|\r)/gm, "");
That should remove all kinds of line breaks.
Line breaks (better: newlines) can be one of Carriage Return (CR, \r, on older Macs), Line Feed (LF, \n, on Unices incl. Linux) or CR followed by LF (\r\n, on WinDOS). (Contrary to another answer, this has nothing to do with character encoding.)
Therefore, the most efficient RegExp literal to match all variants is
/\r?\n|\r/
If you want to match all newlines in a string, use a global match,
/\r?\n|\r/g
respectively. Then proceed with the replace method as suggested in several other answers. (Probably you do not want to remove the newlines, but replace them with other whitespace, for example the space character, so that words remain intact.)
var str = " \n this is a string \n \n \n"
console.log(str);
console.log(str.trim());
String.trim() removes whitespace from the beginning and end of strings... including newlines.
const myString = " \n \n\n Hey! \n I'm a string!!! \n\n";
const trimmedString = myString.trim();
console.log(trimmedString);
// outputs: "Hey! \n I'm a string!!!"
Here's an example fiddle: http://jsfiddle.net/BLs8u/
NOTE! it only trims the beginning and end of the string, not line breaks or whitespace in the middle of the string.
You can use \n in a regex for newlines, and \r for carriage returns.
var str2 = str.replace(/\n|\r/g, "");
Different operating systems use different line endings, with varying mixtures of \n and \r. This regex will replace them all.
The simplest solution would be:
let str = '\t\n\r this \n \t \r is \r a \n test \t \r \n';
str = str.replace(/\s+/g, ' ').trim();
console.log(str); // logs: "this is a test"
.replace() with /\s+/g regexp is changing all groups of white-spaces characters to a single space in the whole string then we .trim() the result to remove all exceeding white-spaces before and after the text.
Are considered as white-spaces characters:
[ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]
If you want to remove all control characters, including CR and LF, you can use this:
myString.replace(/[^\x20-\x7E]/gmi, "")
It will remove all non-printable characters. This are all characters NOT within the ASCII HEX space 0x20-0x7E. Feel free to modify the HEX range as needed.
This will replace the line break by empty space.
someText = someText.replace(/(\r\n|\n|\r)/gm,"");
Read more on this article.
var str = "bar\r\nbaz\nfoo";
str.replace(/[\r\n]/g, '');
>> "barbazfoo"
To remove new line chars use this:
yourString.replace(/\r?\n?/g, '')
Then you can trim your string to remove leading and trailing spaces:
yourString.trim()
USE THIS FUNCTION BELOW AND MAKE YOUR LIFE EASY
The easiest approach is using regular expressions to detect and replace newlines in the string. In this case, we use replace function along with string to replace with, which in our case is an empty string.
function remove_linebreaks( var message ) {
return message.replace( /[\r\n]+/gm, "" );
}
In the above expression, g and m are for global and multiline flags
I often use this regex for (html) strings inside jsons:
replace(/[\n\r\t\s]+/g, ' ')
The strings come from a html editor of a CMS or a i18n php. The common scenarios are:
- lorem(.,)\nipsum
- lorem(.,)\n ipsum
- lorem(.,)\n
ipsum
- lorem ipsum
- lorem\n\nipsum
- ... many others with mixed whitespaces (\t\s) and even \r
The regex avoids this ugly things:
lorem\nipsum => loremipsum
lorem,\nipsum => lorem,ipsum
lorem,\n\nipsum => lorem, ipsum
...
Surely not for all use cases and not the fastest one, but enough for most textareas and texts for websites or webapps.
The answer provided by PointedEars is everything most of us need. But by following Mathias Bynens's answer, I went on a Wikipedia trip and found this: https://en.wikipedia.org/wiki/Newline.
The following is a drop-in function that implements everything the above Wiki page considers "new line" at the time of this answer.
If something doesn't fit your case, just remove it. Also, if you're looking for performance this might not be it, but for a quick tool that does the job in any case, this should be useful.
// replaces all "new line" characters contained in `someString` with the given `replacementString`
const replaceNewLineChars = ((someString, replacementString = ``) => { // defaults to just removing
const LF = `\u{000a}`; // Line Feed (\n)
const VT = `\u{000b}`; // Vertical Tab
const FF = `\u{000c}`; // Form Feed
const CR = `\u{000d}`; // Carriage Return (\r)
const CRLF = `${CR}${LF}`; // (\r\n)
const NEL = `\u{0085}`; // Next Line
const LS = `\u{2028}`; // Line Separator
const PS = `\u{2029}`; // Paragraph Separator
const lineTerminators = [LF, VT, FF, CR, CRLF, NEL, LS, PS]; // all Unicode `lineTerminators`
let finalString = someString.normalize(`NFD`); // better safe than sorry? Or is it?
for (let lineTerminator of lineTerminators) {
if (finalString.includes(lineTerminator)) { // check if the string contains the current `lineTerminator`
let regex = new RegExp(lineTerminator.normalize(`NFD`), `gu`); // create the `regex` for the current `lineTerminator`
finalString = finalString.replace(regex, replacementString); // perform the replacement
};
};
return finalString.normalize(`NFC`); // return the `finalString` (without any Unicode `lineTerminators`)
});
Simple we can remove new line by using text.replace(/\n/g, " ")
const text = 'Students next year\n GO \n For Trip \n';
console.log("Original : ", text);
var removed_new_line = text.replace(/\n/g, " ");
console.log("New : ", removed_new_line);
A linebreak in regex is \n, so your script would be
var test = 'this\nis\na\ntest\nwith\newlines';
console.log(test.replace(/\n/g, ' '));
I am adding my answer, it is just an addon to the above,
as for me I tried all the /n options and it didn't work, I saw my text is comming from server with double slash so I used this:
var fixedText = yourString.replace(/(\r\n|\n|\r|\\n)/gm, '');
Try the following code. It works on all platforms.
var break_for_winDOS = 'test\r\nwith\r\nline\r\nbreaks';
var break_for_linux = 'test\nwith\nline\nbreaks';
var break_for_older_mac = 'test\rwith\rline\rbreaks';
break_for_winDOS.replace(/(\r?\n|\r)/gm, ' ');
//output
'test with line breaks'
break_for_linux.replace(/(\r?\n|\r)/gm, ' ');
//output
'test with line breaks'
break_for_older_mac.replace(/(\r?\n|\r)/gm, ' ');
// Output
'test with line breaks'
If it happens that you don't need this htm characte   shile using str.replace(/(\r\n|\n|\r)/gm, "") you can use this str.split('\n').join('');
cheers
1st way:
const yourString = 'How are you \n I am fine \n Hah'; // Or textInput, something else
const newStringWithoutLineBreaks = yourString.replace(/(\r\n|\n|\r)/gm, "");
2nd way:
const yourString = 'How are you \n I am fine \n Hah'; // Or textInput, something else
const newStringWithoutLineBreaks = yourString.split('\n').join('');
On mac, just use \n in regexp to match linebreaks. So the code will be string.replace(/\n/g, ''), ps: the g followed means match all instead of just the first.
On windows, it will be \r\n.
This will remove all your newlines, spaces, unnecessary characters
str = '\n \n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n Books\n \n \n \n \n\n\n'
console.log(str)
var output = str.replace(/\n|\r|\W/g, "");
console.log(output)
'Books'
const text = 'test\nwith\nline\nbreaks'
const textWithoutBreaks = text.split('\n').join(' ')
Related
I have a text in a textarea and I read it out using the .value attribute.
Now I would like to remove all linebreaks (the character that is produced when you press Enter) from my text now using .replace with a regular expression, but how do I indicate a linebreak in a regex?
If that is not possible, is there another way?
How you'd find a line break varies between operating system encodings. Windows would be \r\n, but Linux just uses \n and Apple uses \r.
I found this in JavaScript line breaks:
someText = someText.replace(/(\r\n|\n|\r)/gm, "");
That should remove all kinds of line breaks.
Line breaks (better: newlines) can be one of Carriage Return (CR, \r, on older Macs), Line Feed (LF, \n, on Unices incl. Linux) or CR followed by LF (\r\n, on WinDOS). (Contrary to another answer, this has nothing to do with character encoding.)
Therefore, the most efficient RegExp literal to match all variants is
/\r?\n|\r/
If you want to match all newlines in a string, use a global match,
/\r?\n|\r/g
respectively. Then proceed with the replace method as suggested in several other answers. (Probably you do not want to remove the newlines, but replace them with other whitespace, for example the space character, so that words remain intact.)
var str = " \n this is a string \n \n \n"
console.log(str);
console.log(str.trim());
String.trim() removes whitespace from the beginning and end of strings... including newlines.
const myString = " \n \n\n Hey! \n I'm a string!!! \n\n";
const trimmedString = myString.trim();
console.log(trimmedString);
// outputs: "Hey! \n I'm a string!!!"
Here's an example fiddle: http://jsfiddle.net/BLs8u/
NOTE! it only trims the beginning and end of the string, not line breaks or whitespace in the middle of the string.
You can use \n in a regex for newlines, and \r for carriage returns.
var str2 = str.replace(/\n|\r/g, "");
Different operating systems use different line endings, with varying mixtures of \n and \r. This regex will replace them all.
The simplest solution would be:
let str = '\t\n\r this \n \t \r is \r a \n test \t \r \n';
str = str.replace(/\s+/g, ' ').trim();
console.log(str); // logs: "this is a test"
.replace() with /\s+/g regexp is changing all groups of white-spaces characters to a single space in the whole string then we .trim() the result to remove all exceeding white-spaces before and after the text.
Are considered as white-spaces characters:
[ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]
If you want to remove all control characters, including CR and LF, you can use this:
myString.replace(/[^\x20-\x7E]/gmi, "")
It will remove all non-printable characters. This are all characters NOT within the ASCII HEX space 0x20-0x7E. Feel free to modify the HEX range as needed.
This will replace the line break by empty space.
someText = someText.replace(/(\r\n|\n|\r)/gm,"");
Read more on this article.
var str = "bar\r\nbaz\nfoo";
str.replace(/[\r\n]/g, '');
>> "barbazfoo"
To remove new line chars use this:
yourString.replace(/\r?\n?/g, '')
Then you can trim your string to remove leading and trailing spaces:
yourString.trim()
USE THIS FUNCTION BELOW AND MAKE YOUR LIFE EASY
The easiest approach is using regular expressions to detect and replace newlines in the string. In this case, we use replace function along with string to replace with, which in our case is an empty string.
function remove_linebreaks( var message ) {
return message.replace( /[\r\n]+/gm, "" );
}
In the above expression, g and m are for global and multiline flags
I often use this regex for (html) strings inside jsons:
replace(/[\n\r\t\s]+/g, ' ')
The strings come from a html editor of a CMS or a i18n php. The common scenarios are:
- lorem(.,)\nipsum
- lorem(.,)\n ipsum
- lorem(.,)\n
ipsum
- lorem ipsum
- lorem\n\nipsum
- ... many others with mixed whitespaces (\t\s) and even \r
The regex avoids this ugly things:
lorem\nipsum => loremipsum
lorem,\nipsum => lorem,ipsum
lorem,\n\nipsum => lorem, ipsum
...
Surely not for all use cases and not the fastest one, but enough for most textareas and texts for websites or webapps.
The answer provided by PointedEars is everything most of us need. But by following Mathias Bynens's answer, I went on a Wikipedia trip and found this: https://en.wikipedia.org/wiki/Newline.
The following is a drop-in function that implements everything the above Wiki page considers "new line" at the time of this answer.
If something doesn't fit your case, just remove it. Also, if you're looking for performance this might not be it, but for a quick tool that does the job in any case, this should be useful.
// replaces all "new line" characters contained in `someString` with the given `replacementString`
const replaceNewLineChars = ((someString, replacementString = ``) => { // defaults to just removing
const LF = `\u{000a}`; // Line Feed (\n)
const VT = `\u{000b}`; // Vertical Tab
const FF = `\u{000c}`; // Form Feed
const CR = `\u{000d}`; // Carriage Return (\r)
const CRLF = `${CR}${LF}`; // (\r\n)
const NEL = `\u{0085}`; // Next Line
const LS = `\u{2028}`; // Line Separator
const PS = `\u{2029}`; // Paragraph Separator
const lineTerminators = [LF, VT, FF, CR, CRLF, NEL, LS, PS]; // all Unicode `lineTerminators`
let finalString = someString.normalize(`NFD`); // better safe than sorry? Or is it?
for (let lineTerminator of lineTerminators) {
if (finalString.includes(lineTerminator)) { // check if the string contains the current `lineTerminator`
let regex = new RegExp(lineTerminator.normalize(`NFD`), `gu`); // create the `regex` for the current `lineTerminator`
finalString = finalString.replace(regex, replacementString); // perform the replacement
};
};
return finalString.normalize(`NFC`); // return the `finalString` (without any Unicode `lineTerminators`)
});
Simple we can remove new line by using text.replace(/\n/g, " ")
const text = 'Students next year\n GO \n For Trip \n';
console.log("Original : ", text);
var removed_new_line = text.replace(/\n/g, " ");
console.log("New : ", removed_new_line);
A linebreak in regex is \n, so your script would be
var test = 'this\nis\na\ntest\nwith\newlines';
console.log(test.replace(/\n/g, ' '));
I am adding my answer, it is just an addon to the above,
as for me I tried all the /n options and it didn't work, I saw my text is comming from server with double slash so I used this:
var fixedText = yourString.replace(/(\r\n|\n|\r|\\n)/gm, '');
Try the following code. It works on all platforms.
var break_for_winDOS = 'test\r\nwith\r\nline\r\nbreaks';
var break_for_linux = 'test\nwith\nline\nbreaks';
var break_for_older_mac = 'test\rwith\rline\rbreaks';
break_for_winDOS.replace(/(\r?\n|\r)/gm, ' ');
//output
'test with line breaks'
break_for_linux.replace(/(\r?\n|\r)/gm, ' ');
//output
'test with line breaks'
break_for_older_mac.replace(/(\r?\n|\r)/gm, ' ');
// Output
'test with line breaks'
If it happens that you don't need this htm characte   shile using str.replace(/(\r\n|\n|\r)/gm, "") you can use this str.split('\n').join('');
cheers
1st way:
const yourString = 'How are you \n I am fine \n Hah'; // Or textInput, something else
const newStringWithoutLineBreaks = yourString.replace(/(\r\n|\n|\r)/gm, "");
2nd way:
const yourString = 'How are you \n I am fine \n Hah'; // Or textInput, something else
const newStringWithoutLineBreaks = yourString.split('\n').join('');
On mac, just use \n in regexp to match linebreaks. So the code will be string.replace(/\n/g, ''), ps: the g followed means match all instead of just the first.
On windows, it will be \r\n.
This will remove all your newlines, spaces, unnecessary characters
str = '\n \n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n Books\n \n \n \n \n\n\n'
console.log(str)
var output = str.replace(/\n|\r|\W/g, "");
console.log(output)
'Books'
const text = 'test\nwith\nline\nbreaks'
const textWithoutBreaks = text.split('\n').join(' ')
I'm trying to compare value of text inside div (This is a sentence.) and text defined in js variable:
function isSame(){
s="This is a sentence."
var text1 = $('#right').text();
var t1 = text1.replace(/ /g,'').replace(/ /g, '').replace(/\<br\s*[\/]?>/gi, '').replace('\t','');
var s1 = s.replace(/ /g,'').replace(/ /g, '').replace(/\<br\s*[\/]?>/gi, '').replace('\t','');
console.log(s1+" VS "+ t1);
if (t1 == s1){
console.log("Same");
} else {
console.log("Not same...");
}
}
All the .replace are because on console I had extra tabs in div (which has style in it) I had extra spaces. Console log shows:
Thisisasentence. VS
Thisisasentence.
Not same...
What is it I'm missing?
Instead of this entire regular expression, have you tried using the trim() method?
As stated in the documentation for String.prototype.trim(), in MDN:
The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).
I believe your code should then be reduced to:
function isSame() {
var s = "This is a sentence.";
var text1 = $('#right').text();
console.log(s1 + " VS " + t1);
if (text1.trim() === s1) {
console.log("Same");
} else {
console.log("Not the same...");
}
}
And the comparison would work as expected.
Update:
As already mentioned in further answers by Ysharp and Rob Brander, you could increment your regular expression by expanding it to other match new lines and carriage return elements. That would change your current regex by adding a \s+ matcher to it, resulting in:
replace(/\s+/g, '')
Your regular expressions look like they're trying to replace any whitespace characters. I would suggest using \s as part of your regular expression, because that looks for all permutations of whitespace.
Your two strings are not equal because there is a newline before and after the phrase. You could try replacing just the new lines with .replace('\n', '')
You tried to get rid of whitespace using
replace(/ /g, '')
but as others pointed out, this is not sufficient to get rid of carriage returns and/or newlines.
Try this instead:
replace(/\s+/g, '')
which will take care of stripping out all of the '\t', '\n', etc, everywhere in the strings it is applied to.
'HTH,
Hi I am getting new line(\n) and tab(\t) characters between words and I was trying to trim those by using $.trim() function but its not working. So can anyone have some solution for this type of problem.
Ex:
var str = "Welcome\n\tTo\n\nBeautiful\t\t\t\nWorld";
alert($.trim(str));
the above code is not working.
str.replace(/\s+/g, " "); //try this
reference replace
\s matches any newline or tab or white-space
You can do this:
var str = "Welcome\n\tTo\n\nBeautiful\t\t\t\nWorld";
alert($.trim(str.replace(/[\t\n]+/g,' ')));
// results is "Welcome To Beautiful World"
That is expected. trim only takes care of leading and trailing whitespace.
Instead, use
str.split(/\s/).join(' ');
In your example, this returns
"Welcome To Beautiful World"
You can use replace with a regular expression :
var str = "Welcome\n\tTo\n\nBeautiful\t\t\t\nWorld";
alert($.trim(str.replace(/[\t\n]+/g, ' ')));
Demo
I have strings with extra whitespace characters. Each time there's more than one whitespace, I'd like it be only one. How can I do this using JavaScript?
Something like this:
var s = " a b c ";
console.log(
s.replace(/\s+/g, ' ')
)
You can augment String to implement these behaviors as methods, as in:
String.prototype.killWhiteSpace = function() {
return this.replace(/\s/g, '');
};
String.prototype.reduceWhiteSpace = function() {
return this.replace(/\s+/g, ' ');
};
This now enables you to use the following elegant forms to produce the strings you want:
"Get rid of my whitespaces.".killWhiteSpace();
"Get rid of my extra whitespaces".reduceWhiteSpace();
Here's a non-regex solution (just for fun):
var s = ' a b word word. word, wordword word ';
// with ES5:
s = s.split(' ').filter(function(n){ return n != '' }).join(' ');
console.log(s); // "a b word word. word, wordword word"
// or ES2015:
s = s.split(' ').filter(n => n).join(' ');
console.log(s); // "a b word word. word, wordword word"
Can even substitute filter(n => n) with .filter(String)
It splits the string by whitespaces, remove them all empty array items from the array (the ones which were more than a single space), and joins all the words again into a string, with a single whitespace in between them.
using a regular expression with the replace function does the trick:
string.replace(/\s/g, "")
I presume you're looking to strip spaces from the beginning and/or end of the string (rather than removing all spaces?
If that's the case, you'll need a regex like this:
mystring = mystring.replace(/(^\s+|\s+$)/g,' ');
This will remove all spaces from the beginning or end of the string. If you only want to trim spaces from the end, then the regex would look like this instead:
mystring = mystring.replace(/\s+$/g,' ');
Hope that helps.
jQuery.trim() works well.
http://api.jquery.com/jQuery.trim/
I know I should not necromancy on a subject, but given the details of the question, I usually expand it to mean:
I want to replace multiple occurences of whitespace inside the string with a single space
...and... I do not want whitespaces in the beginnin or end of the string (trim)
For this, I use code like this (the parenthesis on the first regexp are there just in order to make the code a bit more readable ... regexps can be a pain unless you are familiar with them):
s = s.replace(/^(\s*)|(\s*)$/g, '').replace(/\s+/g, ' ');
The reason this works is that the methods on String-object return a string object on which you can invoke another method (just like jQuery & some other libraries). Much more compact way to code if you want to execute multiple methods on a single object in succession.
var x = " Test Test Test ".split(" ").join("");
alert(x);
Try this.
var string = " string 1";
string = string.trim().replace(/\s+/g, ' ');
the result will be
string 1
What happened here is that it will trim the outside spaces first using trim() then trim the inside spaces using .replace(/\s+/g, ' ').
How about this one?
"my test string \t\t with crazy stuff is cool ".replace(/\s{2,9999}|\t/g, ' ')
outputs "my test string with crazy stuff is cool "
This one gets rid of any tabs as well
If you want to restrict user to give blank space in the name just create a if statement and give the condition. like I did:
$j('#fragment_key').bind({
keypress: function(e){
var key = e.keyCode;
var character = String.fromCharCode(key);
if(character.match( /[' ']/)) {
alert("Blank space is not allowed in the Name");
return false;
}
}
});
create a JQuery function .
this is key press event.
Initialize a variable.
Give condition to match the character
show a alert message for your matched condition.
I want to remove all unnecessary commas from the start/end of the string.
eg; google, yahoo,, , should become google, yahoo.
If possible ,google,, , yahoo,, , should become google,yahoo.
I've tried the below code as a starting point, but it seems to be not working as desired.
trimCommas = function(s) {
s = s.replace(/,*$/, "");
s = s.replace(/^\,*/, "");
return s;
}
In your example you also want to trim the commas if there's spaces between them at the start or at the end, use something like this:
str.replace(/^[,\s]+|[,\s]+$/g, '').replace(/,[,\s]*,/g, ',');
Note the use of the 'g' modifier for global replace.
You need this:
s = s.replace(/[,\s]{2,}/,""); //Removes double or more commas / spaces
s = s.replace(/^,*/,""); //Removes all commas from the beginning
s = s.replace(/,*$/,""); //Removes all commas from the end
EDIT: Made all the changes - should work now.
My take:
var cleanStr = str.replace(/^[\s,]+/,"")
.replace(/[\s,]+$/,"")
.replace(/\s*,+\s*(,+\s*)*/g,",")
This one will work with opera, internet explorer, whatever
Actually tested this last one, and it works!
What you need to do is replace all groups of "space and comma" with a single comma and then remove commas from the start and end:
trimCommas = function(str) {
str = str.replace(/[,\s]*,[,\s]*/g, ",");
str = str.replace(/^,/, "");
str = str.replace(/,$/, "");
return str;
}
The first one replaces every sequence of white space and commas with a single comma, provided there's at least one comma in there. This handles the edge case left in the comments for "Internet Explorer".
The second and third get rid of the comma at the start and end of string where necessary.
You can also add (to the end):
str = str.replace(/[\s]+/, " ");
to collapse multi-spaces down to one space and
str = str.replace(/,/g, ", ");
if you want them to be formatted nicely (space after each comma).
A more generalized solution would be to pass parameters to indicate behaviour:
Passing true for collapse will collapse the spaces within a section (a section being defined as the characters between commas).
Passing true for addSpace will use ", " to separate sections rather than just "," on its own.
That code follows. It may not be necessary for your particular case but it might be better for others in terms of code re-use.
trimCommas = function(str,collapse,addspace) {
str = str.replace(/[,\s]*,[,\s]*/g, ",").replace(/^,/, "").replace(/,$/, "");
if (collapse) {
str = str.replace(/[\s]+/, " ");
}
if (addspace) {
str = str.replace(/,/g, ", ");
}
return str;
}
First ping on Google for "Javascript Trim": http://www.somacon.com/p355.php. You seem to have implemented this using commas, and I don't see why it would be a problem (though you escaped in the second one and not in the first).
Not quite as sophisticated, but simple with:
',google,, , yahoo,, ,'.replace(/\s/g, '').replace(/,+/g, ',');
You should be able to use only one replace call:
/^( *, *)+|(, *(?=,|$))+/g
Test:
'google, yahoo,, ,'.replace(/^( *, *)+|(, *(?=,|$))+/g, '');
"google, yahoo"
',google,, , yahoo,, ,'.replace(/^( *, *)+|(, *(?=,|$))+/g, '');
"google, yahoo"
Breakdown:
/
^( *, *)+ # Match start of string followed by zero or more spaces
# followed by , followed by zero or more spaces.
# Repeat one or more times
| # regex or
(, *(?=,|$))+ # Match , followed by zero or more spaces which have a comma
# after it or EOL. Repeat one or more times
/g # `g` modifier will run on until there is no more matches
(?=...) is a look ahead will will not move the position of the match but only verify that a the characters are after the match. In our case we look for , or EOL
match() is much better tool for this than replace()
str = " aa, bb,, cc , dd,,,";
newStr = str.match(/[^\s,]+/g).join(",")
alert("[" + newStr + "]")
When you want to replace ",," ",,,", ",,,," and ",,,,," below code will be removed by ",".
var abc = new String("46590,26.91667,75.81667,,,45346,27.18333,78.01667,,,45630,12.97194,77.59369,,,47413,19.07283,72.88261,,,45981,13.08784,80.27847,,");
var pqr= abc.replace(/,,/g,',').replace(/,,/g, ',');
alert(pqr);