Home > Enterprise >  Split a string by space but keep space after reach element - Javascript
Split a string by space but keep space after reach element - Javascript

Time:07-21

I am trying to split a string by space but keep the space after each element. So 'This is a string' would become ['This ', 'is ', 'a ', 'string']. The input string could contain words, numbers, or special characters.

Right now I have:

var words = text.split(/(\w \s)/).filter(x => x !== '');

The above works, but the regex split gives you ['This ', '', 'is ', '', 'a ', '', 'string'] and requires use of .filter to delete the empty string elements. I bet there is a better regex, but I'm not familiar enough with regex to figure it out.

CodePudding user response:

You can use a lookbehind as the regular expression to split on, so that the delimiter doesn't use any characters in the string.

const text = 'This is a   string';
const words = text.split(/(?<=\s)/);
console.log(words);

CodePudding user response:

var text = 'This is a string'
var words = text.split(/\s /).map(item => item   ' ')
console.log(words)

  • Related