In Javascript, a string prototype has two methods that can control this:
str.trim().replace(/\s+/g, ' ')
str.trim() will remove leading and trailing spaces
str.replace(regex, replacement) will return a new line (non-destructive for the original str ), where regex will be compared with the provided string, and the first instance of the match will be replaced with replacement , then the whole new line will be returned.
It is important to note: the first .replace parameter .replace not be enclosed in quotation marks. The regular expression is divided by slashes ( /regex/ ), and then g added to mean replacing globally (each matched instance), and not just replacing the first or next instance based on lastIndex (which is initially 0, which gives the first instance). You can learn more about lastIndex and everything that I mentioned in the second link.
Example:
var str = ' 1 2 3 4 ' function trimReplace(str){ newStr = str.trim().replace(/\s+/g, ' '); console.log(newStr); } trimReplace(str)
Try this in the console: ' 1 2 3 4 '.trim().replace(/\s+/g, ' ')
"1 2 3 4"
_
regex: kleene statements help you understand the regex used to match multiple spaces
regex: a useful guide to regular expression and / g flag
Google: MDN string.protoype.trim ()
Google: MDN string.prototype.replace ()
source share