Unicorn
Unicorn

Reputation: 295

How do I split a letter and number?

I have this string

let tmp = "abcd1234";

I tried below code but didnt worked. can anyone pls. advice.

let tmp = "abcd1234"; 
var alphas = tmp.split("(?<=\\D)(?=\\d");
console.log(alphas[0],'---',alphas[1])

Its returning "abcd1234 --- undefined"

Thanks in Advance.

Upvotes: 0

Views: 73

Answers (6)

Emmy O
Emmy O

Reputation: 1

const tmp = "abcdABCD1234";    
const [alpha, numeric] = tmp.split(/(\d+)/);    
console.log(alpha, '---', numeric);

Upvotes: 0

LordRasta
LordRasta

Reputation: 15

Could you use Regex? this could be a starter solution

let tmp = "abcd1234"; 
var n = /\d+/.exec(tmp);
var c = /[a-zA-Z]+/.exec(tmp);
console.log(n[0],'---',c[0])

From here you should to control if there are multiples matches and so on.

Note: \D+ will match every caracter non digit so =+. etc will match.

More Regex info: here

Regex playground : here

Upvotes: 0

Mark
Mark

Reputation: 5239

Your regex is (?<=\\D)(?=\\d, it appears that you're missing a closing bracket ) at the end of your regex. The complete regex then becomes (?<=\\D)(?=\\d).

Also you're enclosing your regex in "regex" and it should be enclosed in /regex/

let tmp = "abcd1234"; 
var alphas = tmp.split(/(?<=\D)(?=\d)/);
console.log(alphas);
console.log(alphas[0],'---',alphas[1])

Based on a comment by @trichetriche who said positive lookbehind is not supported on all browsers, a simpler method would be to enclose the letters and numbers within their own capturing group like this:

const regex = /(\D+)(\d+)/;
const str = "abcd1234";
let alphas = regex.exec(str);

console.log(alphas[1], '---', alphas[2])

Upvotes: 1

Artyom Amiryan
Artyom Amiryan

Reputation: 2966

let tmp = "abcd1234";
var alphas = tmp.split(/(\d+)/);
console.log(alphas[0], '---', alphas[1])

simple regexp /(\d+)/ that will find numbers in row and split from letters

Upvotes: 1

vancho
vancho

Reputation: 76

You can do it with regex too:

let tmp = "abcd1234"; 
let myRegexp = /([a-z]+)([1-9]+)/;
var match = myRegexp.exec(tmp);
console.log(match[1],'---',match[2])

Upvotes: 0

user4676340
user4676340

Reputation:

If you're sure you will have alpha, then numeric, then look for the point where it changes, append a space, then split on it :

const tmp = "abcd1234";
const [alpha, numeric] = tmp.replace(/(\D)(\d)/, '$1 $2').split(' ');
console.log(alpha, '---', numeric);

Upvotes: 2

Related Questions