简体   繁体   中英

How to remove whitespace chunks ending with a newline from string?

I am having a trouble with removing all spaces from a string.

Stehn        
Stehn        
Simchart
Simchart
Stehn        
Stehn        
Stehn        
Stehn        
Stehn  

This is the string, which has new lines, spaces, and so on.

string.replace(/[\r\n]+/gm, ', ')

Doing this, only returns me

Stehn, Stehn, Simchart, Simchart, Stehn, Stehn, Orion Reederei GmbH & Co KG, Orion Reederei GmbH & Co KG, Stehn, Stehn, Stehn, Arrow Shipping Germany, "

But I would like to get a normalized and sanitized string with commas.

string.replace(/\r?\n|\r/g, ',').split(',').map(s => s.trim()).join(', ')

This code, however, resolves my problem, but I don't like this solution as I have thousands inside my table.

We can just try replacing all whitespace along with an immediately following CR?LF with just a single comma and space.

 var input = "Stehn \nStehn \nSimchart\nSimchart\nStehn \nStehn \nStehn \nStehn \nStehn "; var output = input.replace(/\s*?\r?\n/g, ", "); console.log(output);

You could use a single pattern, and in the replacement use a comma and a single space.

[^\S\r\n]*[\r\n]+
  • [^\S\r\n]* Negated character class , match 0+ times a whitespace char except newlines
  • [\r\n]+ Match 1+ newlines (for a single newline, use \r?\n )

Regex demo

 const regex = /[^\S\r\n]*[\r\n]+/g; const str = `Stehn Stehn Simchart Simchart Stehn Stehn Stehn Stehn Stehn `; const result = str.replace(regex, `, `); console.log(result);

If your string is:

let s = "a     b     c         d    e   \nf    g  h\n\ni";

Then you can strip with:

s.split(/\s+/)

And combine:

s.split(/\s+/).join(',');

If instead it's a newline thing and you want to trim, then why not just split? Easier than replacing, splitting, trimming, and rejoining:

s.split(/\r?\n|\r/).map(s => s.trim()).join(', ')

Since you want to substitute whitespace with , you must write a regex that matches whitespaces

Regex: /\b\s+\b/gm

g: global mode

m: multiline mode

Now at this point your regex should match all the spaces. Now all you have to do is replace them with ,

Note that I am using word boundaries here since you do not want , at the end of your last string.

Try this.

function removeAllBlankSpaces(str) {
   return str.split('').filter(s => s != ' ').join('');
}

console.log(removeAllBlankSpaces('str ing');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM