Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
52
rated 0 times [  55] [ 3]  / answers: 1 / hits: 15123  / 10 Years ago, sat, august 9, 2014, 12:00:00

I'm trying to split some text either by whitespace and/or new line, and also remove the white space before and after the whole text, just in case. I'm not sure how to perform this as I cannot get my head around regex (I've tried other people's regex but it breaks my output) and I want to perform this using best practice rather than writing some lengthy buggy workaround



My code can be located here: https://github.com/Dave-Melia/Text-Separator



Many thanks



D


More From » regex

 Answers
3

To split on any whitespace (including newlines), you'd use /s/ with split:



var theArray = theString.split(/s+/);


s means spaces (e.g., whitespace — including newlines), and + means one or more.



To trim whitespace from the beginning and end of the string first, on any modern browser you can use String#trim:



var theArray = theString.trim().split(/s+/);


If you have to support older browsers, you can use replace:



var theArray = theString.replace(/^s+|s+$/g, '').split(/s+/);


That regex used with replace can use a bit of explanation: http://regex101.com/r/sS0zV3/1




  • ^s+ means any whitespace at the beginning of the string

  • | means or (as in , this or that) (it's called an alternation)

  • s+$ means any whitepsace at the end of the string



Then we replace all occurrences (g) with '' (a blank string).


[#69848] Thursday, August 7, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kiley

Total Points: 733
Total Questions: 118
Total Answers: 94

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
;