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
Pytesseract Ocr Multiple Config Options
Python Script to List Users and Groups
Python Convert Microsoft Office Docs to Plain Text on Linux
Asyncio in Corroutine Runtimeerror: No Running Event Loop
How to Deal with Linux/Python Dependencies
Python: Get Mount Point on Windows or Linux
How to Split My 800X480 5-Inch Screen into 2 Parts
Typeerror: 'Str' Does Not Support the Buffer Interface
Calculate Time Difference Between Two Pandas Columns in Hours and Minutes
How to Find the Mountpoint a File Resides On
Running Process of Remote Ssh Server in the Background Using Python Paramiko
Pyserial Works Fine in Python Interpreter, But Not Standalone
Writing to Shared Memory in Python Is Very Slow
How to Find the Target File's Full(Absolute Path) of the Symbolic Link or Soft Link in Python