1

I would like to split a word by numbers, but at the same time keep the numbers in node.js.

For example, take this following sentence:

var a = "shuan3jia4";

What I want is:

"shuan3 jia4"

However, if you use a regexp's split() function, the numbers that are used on the function are gone, for example:

s.split(/[0-9]/)

The result is:

[ 'shuan', 'jia', '' ]

So is there any way to keep the numbers that are used on the split?

arhak
  • 2,488
  • 1
  • 24
  • 38
Blaszard
  • 30,954
  • 51
  • 153
  • 233
  • @arhak has provided an answer, but to clarify: do you want `['shuan', '3', 'jia', '4']`, or `['shuan3', 'jia4']`? – Robo Mop Mar 24 '18 at 03:55
  • @CoffeehouseCoder `['shuan3', 'jia4']` – Blaszard Mar 24 '18 at 03:57
  • Possible duplicate of [Javascript and regex: split string and keep the separator](https://stackoverflow.com/questions/12001953/javascript-and-regex-split-string-and-keep-the-separator) – arhak Mar 24 '18 at 05:01

4 Answers4

4

You can use match to actually split it per your requirement:

var a = "shuan3jia4";
console.log(a.match(/[a-z]+[0-9]/ig));
james_bond
  • 6,778
  • 3
  • 28
  • 34
3

use parenthesis around the match you wanna keep

see further details at Javascript and regex: split string and keep the separator

var s = "shuan3jia4";
var arr = s.split(/([0-9])/);
console.log(arr);
arhak
  • 2,488
  • 1
  • 24
  • 38
  • 1
    Surprised this gets upvotes. OP specified the output they need clearly and this doesn't produce that output. – Vasan Mar 24 '18 at 04:16
0

var s = "shuan3jia4";
var arr = s.split(/(?<=[0-9])/);
console.log(arr);

This will work as per your requirements. This answer was curated from @arhak and C# split string but keep split chars / separators

As @codybartfast said, (?<=PATTERN) is positive look-behind for PATTERN. It should match at any place where the preceding text fits PATTERN so there should be a match (and a split) after each occurrence of any of the characters.

Haardik
  • 187
  • 1
  • 13
0

Split, map, join, trim.

const a = 'shuan3jia4';

const splitUp = a.split('').map(function(char) {
    if (parseInt(char)) return `${char} `;
    return char;
});

const joined = splitUp.join('').trim();

console.log(joined);
Ezra Chang
  • 1,268
  • 9
  • 12