Is There a Simple Way to Remove Multiple Spaces in a String

Is there a simple way to remove multiple spaces in a string?

>>> import re
>>> re.sub(' +', ' ', 'The quick brown fox')
'The quick brown fox'

How do I replace multiple spaces with a single space in C#?

string sentence = "This is a sentence with multiple    spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
sentence = regex.Replace(sentence, " ");

How to remove multiple spaces in Strings with Swift 2

In Swift 2, join has become joinWithSeparator and you call it on the array.

In filter, isEmpty should be called on the current iteration item $0.

To replace whitespaces and newline characters with unique space characters as in your question:

extension String {
func condenseWhitespace() -> String {
let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return components.filter { !$0.isEmpty }.joinWithSeparator(" ")
}
}

let result = "Hello World.\nHello!".condenseWhitespace() // "Hello World. Hello!"

Because your function does not take any parameter you could make it a property instead:

extension String {
var condensedWhitespace: String {
let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return components.filter { !$0.isEmpty }.joinWithSeparator(" ")
}
}

let result = "Hello World.\nHello!".condensedWhitespace // "Hello World. Hello!"

In Swift 3 there's even more changes.

Function:

extension String {
func condenseWhitespace() -> String {
let components = self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
}

let result = "Hello World.\nHello!".condenseWhitespace()

Property:

extension String {
var condensedWhitespace: String {
let components = self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
}

let result = "Hello World.\nHello!".condensedWhitespace

In Swift 4.2 NSCharacterSet is now CharacterSet, and you can omit and use dot syntax:

extension String {
func condenseWhitespace() -> String {
let components = self.components(separatedBy: .whitespacesAndNewlines)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
}

let result = "Hello World.\nHello!".condenseWhitespace() // "Hello World. Hello!"

Python fastest way to remove multiple spaces in a string

Just a small rewrite of the suggestion up there, but just because something has a small fault doesn't mean you should assume it won't work.

You could easily do something like:

front_space = lambda x:x[0]==" "
trailing_space = lambda x:x[-1]==" "
" "*front_space(text)+' '.join(text.split())+" "*trailing_space(text)

Substitute multiple whitespace with single whitespace in Python

A simple possibility (if you'd rather avoid REs) is

' '.join(mystring.split())

The split and join perform the task you're explicitly asking about -- plus, they also do the extra one that you don't talk about but is seen in your example, removing trailing spaces;-).

stringr - remove multiple spaces, but keep linebreaks (\n, \r)

With stringr, you may use \h shorthand character class to match any horizontal whitespaces.

library(stringr)
x <- "hello \n\r how are you \n\r all good?"
x <- str_replace_all(x, "\\h+", " ")
## [1] "hello \n\r how are you \n\r all good?"

In base R, you may use it, too, with a PCRE pattern:

gsub("\\h+", " ", x, perl=TRUE)

See the online R demo.

If you plan to still match any whitespace (including some Unicode line breaks) other than CR and LF symbols, you may plainly use [^\S\r\n] pattern:

str_replace_all(x, "[^\\S\r\n]+", " ")
gsub("[^\\S\r\n]+", " ", x, perl=TRUE)

How To Remove Multiple Spaces from String jQuery

I've changed your replace with a regex. This removes all the spaces


$("#MyTextBox").blur(function(){
var myValue = $(this).val();
alert(myValue);
var test = myValue.replace(/\s/g, '');
alert(test);
$("#MyTextBox").val(test);
});


Related Topics



Leave a reply



Submit