Eddie Brunstedt
Eddie Brunstedt

Reputation: 57

How to create an array out of a string and keep spaces & punctuation at the end of each word?

Take this string as example:

'The strong, fast and gullible cat ran over the street!'

I want to create a function that takes this string and creates the following array:

['The ','strong, ','fast ','and ','gullible ','cat ','ran ','over ','the ','street!']

Observe that I want to keep each puctuation and space after each word.

Upvotes: 1

Views: 105

Answers (4)

talemyn
talemyn

Reputation: 7950

Gonna toss my solution into the ring as well. :)

var sTestVal = 'The strong, fast and gullible cat ran over the street!';
var regexPattern = /[^ ]+( |$)/g;
var aResult = sTestVal.match(regexPattern)

console.log(aResult);

The result is:

["The ", "strong, ", "fast ", "and ", "gullible ", "cat ", "ran ", "over ", "the ", "street!"]

The regex pattern breaks down like this:

[^ ]+ - matches one or more non-space characters, and then

( |$) - either a space or the end of the string

g - it will match all instances of the patternthe end

Upvotes: 1

Scott Marcus
Scott Marcus

Reputation: 65806

As @Summoner commented (while I was modifying my code to do it), if we add some char(s) that we want to use as a delimiter, we can then split on that, rather than the spaces.

var s= 'The strong, fast and gullible cat ran over the street!';
s = s.replace(/\s+/g, " **");
var ary = s.split("**");
console.log(ary);

Upvotes: 1

Oriol
Oriol

Reputation: 288100

You can split at word boundaries followed by a word character:

var str = 'The strong, fast and gullible cat ran over the street!';
console.log(str.split(/\b(?=\w)/));

Upvotes: 2

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

This regular expression will match what you want: /[^\s]+\s*/g;

EXAPMLE:

var str = 'The strong, fast and gullible cat ran over the street!';
var result = str.match(/[^\s]+\s*/g);

console.log(result);

Upvotes: 3

Related Questions