Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate characters and numbers from a string

I have a string variable that contain character and numbers like this

var sampleString = "aaa1211"

Note that variable always start with a character/s and end with number/s. Character and number size is not fixed. It could be something like followings

var sampleString = "aaaaa12111"
var sampleString = "aaa12111"

I need to separate the characters and numbers and assign them into separate variables.

How could I do that ?

I try to use split and substring but for this scenario I couldn't apply those. I know this is a basic question but i'm search over the internet and I was unable to find an answer.

Thank you

like image 876
Sachila Ranawaka Avatar asked Mar 26 '26 05:03

Sachila Ranawaka


2 Answers

Please use [A-Za-z] - all letters (uppercase and lowercase) [0-9] - all numbers

        function myFunction() {
        var str = "aaaaAZE12121212";
        var patt1 = /[0-9]/g;
        var patt2 = /[a-zA-Z]/g;
        var letters = str.match(patt2);
        var digits = str.match(patt1);
        document.getElementById("alphabets").innerHTML = letters;
     document.getElementById("numbers").innerHTML = digits;
    }

Codepen-http://codepen.io/nagasai/pen/pbbGOB

like image 110
Naga Sai A Avatar answered Mar 27 '26 17:03

Naga Sai A


A shorter solution if the string always starts with letters and ends with numbers as you say:

var str = 'aaaaa12111';

var chars = str.slice(0, str.search(/\d/));
var numbs = str.replace(chars, '');

console.log(chars, numbs);
like image 25
Marty Avatar answered Mar 27 '26 19:03

Marty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!