2

So I am parsing a string and I am tokenizing it using | as a delimiter. However, I want to make sure that I do not parse spaces ( in any amount ) and simply ignore them. However for some reason, nothing is working completely. Some spaces escape the check and get printed. here is my code:

white = value;
white.replace(/(^\s+|\s+$)/g, '');
if(white != null && white != '' && white != ' '){
   console.log("IT IS NOT EMPTY");
}else{
   console.log("IT IS EMPTY");
}

I cannot understand it.

These work:

" | "
" | | | "

BUT

" |   | | | " 

does NOT work...

Any suggestions?

Shmiddty
  • 13,847
  • 1
  • 35
  • 52
Georgi Angelov
  • 4,338
  • 12
  • 67
  • 96

2 Answers2

4

.replace does not transform the string, it returns the new string.

white = white.replace(/^\s+|\s+$/g,"");
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • That will remove spaces **only** from the beginning of the string and the end of the string, not between `|` characters. – T.J. Crowder Sep 24 '13 at 21:21
  • my goal is to determine if | | | | | contains only whitespaces. or either of the parts is composed only of white spaces hence "dasdsa| |dasds | | " will evaluate to empty 3 times. – Georgi Angelov Sep 24 '13 at 21:38
0

If your goal is to break the string into parts based on the |, ignoring spaces before or after it, then:

var parts = value.split(/\s*\|\s*/);

That expression says: Split on optional whitespace followed by a literal | (you have to escape them in regular expressions) followed by optional whitespace.

If your goal is to remove spaces that are adjacent to a | from the string, then:

white = value.replace(/(?:\s+\|)|(?:\|\s+)/g, "|");

That regular expression says: If you find a sequence of spaces followed by a literal |, or a sequence of space following a literal |, replace them (including the |) with a single |. The unescaped | within the expression is an "alternation" meaning "either of the things on either side of me."

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875