JavaScript: Split string by characters only or by characters + number if present

How can I split JavaScript string by characters OR by characters+numbers if present?

Example:

Just characters:

var items = "asdaasf"; //I am using items.split('');

so that's okay.

Now if I have numbers:

var items = "a2sdaa5sf";

I want it to split into array so I have result like:

[a2,s,d,a,a5,s,f]

So that it counts as 1 character if letter is followed by a number.

Would I use regex? What would syntax be? I am not too familiar with RegEx.

Answer1:

Split on every position where the following character is a letter. This can be done with a <strong>lookahead</strong>:

> "a2sd12a3".split(/(?=[a-z])/i) ["a2", "s", "d12", "a3"]

Answer2:

If you would just like to split it by character or character followed by number

var reg = /([a-z]\d*)/g; var myString = 'something' myString.match(reg)

@Felix Kling answer is more elegant with the lookahead , but if you want to stick to simplest possible, assuming it always starts with a character.

Answer3:

Similar approach to Abraham Adam's, but updated to include case-insensitivity, by using the following regex: /[a-z]\d*/ig

var regexVal = /[a-z]\d*/ig; var test1 = "asdaasf"; var test2 = "a2sdaa5sf"; var test3 = "a2sd12a3"; var test4 = "a1b2c3de45f6gh78i9j0"; var test5 = "a1b2c3De45f6gH78I9j0"; console.log(test1.match(regexVal)); // ["a", "s", "d", "a", "a", "s", "f"] console.log(test2.match(regexVal)); // ["a2", "s", "d", "a", "a5", "s", "f"] console.log(test3.match(regexVal)); // ["a2", "s", "d12", "a3"] console.log(test4.match(regexVal)); // ["a1", "b2", "c3", "d", "e45", "f6", "g", "h78", "i9", "j0"] console.log(test5.match(regexVal)); // ["a1", "b2", "c3", "D", "e45", "f6", "g", "H78", "I9", "j0"]

Answer4:

To complement @FelixKling's answer, without relying exclusively on a regex, you can reproduce the logic fairly easily:

var input = "a1b2c3de45f6gh78i9j0"; var chunks = []; var accum = ""; var lastWasDigit = false; var isDigitRex = /[0-9]/; Array.from(input).forEach(function (i) { var isDigit = isDigitRex.exec(i); if (lastWasDigit && !isDigit) { chunks.push(accum); accum = "" + i; } else { accum += i; } lastWasDigit = isDigit; }) console.log(chunks);

人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:JavaScript: Split string by characters only or by characters + number if present