skip to Main Content

I need to get separate numbers + special characters + letters from a string with numbers, letters, and special characters. My attempt

var chars = str.slice(0, str.search(/[a-zA-Z]+/));
var numbs = str.replace(chars, '');

The code does not work in case there are no letters.
example of how it should work

'123.331abc' -> '123.331' + 'abc'
'12331abc123' -> '12331' + 'abc123'

3

Answers


  1. const test = "123.887azee7";
    const firstLetterIndex = test.search(/[a-zA-Z]/); // return the index of the first letter found, "-1" otherwise
    

    then you just use String.prototype.substring()

    if (firstLetterIndex !== -1) {
        const firstSubstring = test.substring(0, firstLetterIndex); //  out put 123.887
        const secondSubstring = test.substring(firstLetterIndex); // output azee7
    } else {
        console.log('no letters founed');
        // or do whatever you want
    }
    
    Login or Signup to reply.
  2. Match the first part, then .slice() to get the second:

    const [firstPart] = string.match(/^[^a-z]*/i);
    const secondPart = string.slice(firstPart.length);
    

    ^[^a-z]* means 0 or more non-letter at the beginning. Due to the nature of the * quantifier, this will always match, resulting in a match array whose first element is the first part.

    Try it:

    console.config({ maximize: true });
    
    const testcases = [
        '12331abc123',
        '123.331abc',
        'abc123',
        'abc',
        '123',
    ];
    
    function splitBeforeFirstLetter(string) {
      const [firstPart] = string.match(/^[^a-z]*/i);
      const secondPart = string.slice(firstPart.length);
      
      return [firstPart, secondPart];
    }
    
    testcases.forEach(
      testcase => console.log(testcase, splitBeforeFirstLetter(testcase))
    );
    <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
    Login or Signup to reply.
  3. You can get the both parts with a regex only:

    const arr = [
      '123.331abc',
      '12331abc123'
    ];
    
    const splitBeforeLetter = str => str.match(/([^A-Za-z]+)(.+)/).slice(1);
    
    console.log(...arr.map(splitBeforeLetter));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search