Home > Net >  How to split a javascript string on spaces and non alphanumeric characters while keeping spaces
How to split a javascript string on spaces and non alphanumeric characters while keeping spaces

Time:12-28

How can I split this javascript string: hello here's johhny! into an array ['hello', '', 'here', ''', 's', '', 'johnny', '!']?

I know you use .split(/(\s )/); for splitting on spaces while preserving them and you use .split(/[^A-Za-z]/) for splitting on non alphanumerics, but how can you combine these statements?

CodePudding user response:

split includes matched groups in the output array so just wrap your second regex with ()

const str = "hello here's johhny!"
const array = str.split(/([^A-Za-z])/).filter(Boolean)
console.log(array)

I added .filter(Boolean) to get rid of the empty string at the end

CodePudding user response:

To split a string into an array using both a regular expression for whitespace characters and a regular expression for non-alphanumeric characters, you can use the String.prototype.split method and pass in a combined regular expression as the argument.

Here's an example of how you can split the string "hello here's johhny!" into an array using a combined regular expression:

const str = "hello here's johhny!";
const result = str.split(/[^A-Za-z]|(\s )/);

console.log(result);  // ['hello', '', 'here', ''', 's', '', 'johnny', '!']

The combined regular expression /[^A-Za-z]|(\s )/ consists of two parts:

  1. [^A-Za-z]: This regular expression matches any character that is not an alphabetic character (A-Z or a-z).
  2. (\s ): This regular expression matches one or more consecutive whitespace characters (such as spaces, tabs, or newlines).

The | symbol is used to separate the two parts of the regular expression, and it indicates that either of the two parts can be matched. This means that the combined regular expression will match either a non-alphabetic character or one or more consecutive whitespace characters.

I hope this helps!

  • Related