Skip to main content

Posts

Showing posts from January, 2015

JavaScript: Trimming Whitespaces (Regular Expression)

For Example We want to tidy up the horizontal indentation of this typed words — all i z dog to be — all i z dog In that case, we need to: Find every more-than-1-whitespace pattern from the string. For that, we can employ regular expression ( RegExp ) method. Replace each with one space character. Replacing string can be achieved using replace() method. Function Snippet function trimSpace(string) { return string.replace(/\s+/g, " "); } Very short. Or, using arrow syntax — const trimSpace = (string) => string.replace(/\s+/g, " ")); What Happened There? The trimSpace function accepts an argument, that is the string we want to trim. Then it will output the trimmed string. The Trimming Process I use /\s+/g to find matching pattern which consists of multiple whitespaces. Let's have a look at every bit of that RegExp pattern and syntax. The opening and closing slashes / / are the iden...
Monkey Raptor uses cookies for analytics, advertisements, and functionality. Privacy Policy