Home > Mobile >  The "no-character space" between two characters in REGEX Javascript
The "no-character space" between two characters in REGEX Javascript

Time:01-27

As we can split an array from a Regex, I try to understand this:

console.log( 'hello'.split(/([a-z])/g) );
// returns ['', 'h', '', 'e', '', 'l', '', 'l', '', 'o', '']

The return should be [ 'h', 'e', 'l', 'l', 'o']

How could I use this "no-character" in a Regex and what it represents in computer science?

I find this: Non-breaking space I tried:

let carac = String.fromCharCode(parseInt('202F', 16));
'hello'.split(carac);

But it not works.

CodePudding user response:

console.log( 'hello'.split(/([a-z])/g) );
// returns ['', 'h', '', 'e', '', 'l', '', 'l', '', 'o', '']

The return should be [ 'h', 'e', 'l', 'l', 'o']

No, it shouldn't. First of all, you're opting in to use a very specific syntax (source):

If separator is a regular expression that contains capturing parentheses ( ), matched results are included in the array.

So you're getting both results (empty strings) and separators (letters). If you omit the capturing parenthesis you'll only get results:

console.log( 'hello'.split(/[a-z]/g) );

Getting [ 'h', 'e', 'l', 'l', 'o'] would mean you're getting the separators only. There isn't such syntax defined. To get those as result you need to use the appropriate separator, which is "none at all" (represented by an empty string):

console.log( 'hello'.split('') );

Last but not least, non-breaking spaces are regular characters such as k or

  •  Tags:  
  • Related