Short answer: in regular expressions, \s matches any single whitespace character (a space, a tab or a line break), \s+ matches one or more of them in a row, and a literal space only matches the space bar character. For example, /\s+/g finds every run of spaces, tabs or newlines in a string. See the MDN reference on character classes.
Regular expressions combine both basic and special characters to detect patterns in strings, some of those patterns include whitespaces.
There are several ways on regular expressions to detect whitespaces, the most used one would be the \s or \s+ since they detect not just whitespaces made by the space bar, but with tab and return key (line jump).
//Has white spaces
const text = "4 Geeks Academy"
const hasSpaces = (str) =>{
const regex = new RegExp("\\s+")
return regex.test(str)
}
console.log(hasSpaces(text))
// Output -> trueRegular Expression (RegEx) for whitespaces
Dealing with spaces is a common action when receiving data from our apps, that's why we need to learn how to detect them. Using RegEx allows us to easily detect the presence of white spaces and deal with them as needed.
We can use different RegEx to achieve this:
\sWill take a single whitespace character, including spaces, tabs and the line jumps made with the "return" button.\s+When added the +, you are stating that can be one, or any amount of whitespaces (spaces, tabs, and line breaks).[\r\n\t\f\v ]This RegEx is equivalent to\sbut we add it for compatibility reasons with older programming languages.\tmatches tabular whitespaces(" "). The\s+will match this as well.\wmatches alphanumeric characters and the underscore (whitespaces not included)
Usually, you'll find the \s and \s+ are the most used ones, since they comprehend the other whitespace patterns we discussed.
Implementation:
In the following example, we'll be checking if a url has whitespaces or not.
const badURL = "https://4geeks.com/how to";
const goodURL = "https://4geeks.com/how-to"
const checkURL = (url) =>{
const regex = /\s/;
if (regex.test(url)) {
return (`Testing '${url}': Whitespace found in the URL.`);
} else {
return (`Testing '${url}': No whitespace found in the URL.`);
}
}
checkURL (badURL)
// Testing 'https://4geeks.com/how to': Whitespace found in the URL.
checkURL (goodURL)
// Testing 'https://4geeks.com/how-to': No whitespace found in the URL.Python version:
import re
#whitespaces
badURL = "https://4geeks.com/how to";
goodURL = "https://4geeks.com/how-to"
def checkURL(url):
regex = r"\s"
match = bool(re.search(regex, url))
if (match == True):
return (f"Testing '{url}': Whitespace found in the URL.")
else:
return (f"Testing '{url}': No whitespace found in the URL.")
print(checkURL(badURL))
# Testing 'https://4geeks.com/how to': Whitespace found in the URL.
print(checkURL(goodURL))
# Testing 'https://4geeks.com/how-to': No whitespace found in the URL.A regular expression (also called regex or regexp) is a way to describe a pattern. It is used to locate or validate specific strings or patterns of text in a sentence, document, or any other character input. You can learn more about Regular Expressions in this RegEx Tutorial.
You can find more articles related to this topic in 4Geeks. Hope you enjoyed the reading and keep on the Geek side!
Detecting whitespace with regex is a skill that shows up again in form validation, URL checks and data cleaning. To learn to code with projects like these and mentor support, compare the available programs.
Frequently asked questions
What is the difference between \s and \S in regex?
\s matches any single whitespace character, while the uppercase \S matches any character that is not whitespace. That makes \S+ useful for grabbing words or tokens between spaces: in JavaScript, "a b\tc".match(/\S+/g) returns ["a", "b", "c"]. The same lowercase and uppercase pairing applies to \d and \D for digits and to \w and \W for word characters.
How do you remove all whitespace from a string with regex?
Replace every whitespace match with an empty string. In JavaScript, use text.replace(/\s+/g, ""); the g flag is required, otherwise only the first match is replaced. In Python, use re.sub(r"\s+", "", text), which replaces all matches by default. To remove whitespace only at the start and end, use trim() in JavaScript or strip() in Python.
How do you match spaces and tabs but not line breaks in regex?
Use the character class [ \t] instead of \s, because \s also matches line breaks such as \n and \r. For example, text.replace(/[ \t]+/g, " ") in JavaScript collapses runs of spaces and tabs into a single space while keeping every line intact. Some engines, like PCRE, offer \h for horizontal whitespace, but JavaScript and Python do not support it.
Why doesn't \s work inside new RegExp() in JavaScript?
Inside a normal string literal, the backslash is an escape character, so "\s+" becomes "s+" and the pattern matches the letter s instead of whitespace. Escape the backslash with new RegExp("\\s+") or use a regex literal such as /\s+/. In Python, write the pattern as a raw string like r"\s+", without the surrounding slashes of JavaScript syntax.
