How do I split a string by whitespace and ignoring leading and trailing whitespace into an array of words using a regular expression?

If you are more interested in the bits that are not whitespace, you can match the non-whitespace instead of splitting on whitespace. ” The quick brown fox jumps over the lazy dog. “.match(/\S+/g); Note that the following returns null: ” “.match(/\S+/g) So the best pattern to learn is: str.match(/\S+/g) || []

How to remove all white space from the beginning or end of a string?

String.Trim() returns a string which equals the input string with all white-spaces trimmed from start and end: ” A String “.Trim() -> “A String” String.TrimStart() returns a string with white-spaces trimmed from the start: ” A String “.TrimStart() -> “A String ” String.TrimEnd() returns a string with white-spaces trimmed from the end: ” A String … Read more

How to remove leading and trailing white spaces from a given html string?

See the String method trim() – https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/Trim var myString = ‘ bunch of <br> string data with<p>trailing</p> and leading space ‘; myString = myString.trim(); // or myString = String.trim(myString); Edit As noted in other comments, it is possible to use the regex approach. The trim method is effectively just an alias for a regex: if(!String.prototype.trim) … Read more

Optional Whitespace Regex

Add a \s? if a space can be allowed. \s stands for white space ? says the preceding character may occur once or not occur. If more than one spaces are allowed and is optional, use \s*. * says preceding character can occur zero or more times. ‘#<a href\s?=”https://stackoverflow.com/questions/14293024/(.*?)” title\s?=”https://stackoverflow.com/questions/14293024/(.*?)”><img alt\s?=”https://stackoverflow.com/questions/14293024/(.*?)” src\s?=”https://stackoverflow.com/questions/14293024/(.*?)”[\s*]width\s?=”150″[\s*]height\s?=”https://stackoverflow.com/questions/14293024/(.*?)”></a>#’ allows an optional … Read more

Efficient way to remove ALL whitespace from String?

This is fastest way I know of, even though you said you didn’t want to use regular expressions: Regex.Replace(XML, @”\s+”, “”); Crediting @hypehuman in the comments, if you plan to do this more than once, create and store a Regex instance. This will save the overhead of constructing it every time, which is more expensive … Read more