M
M
MariaM04792018-07-27 20:39:00
JavaScript
MariaM0479, 2018-07-27 20:39:00

How to get numbers and words from a string?

There is a string from which you need to get numbers and words separately. Here is my solution, but unfortunately I can’t understand why the text remains, if it is clear that the regular expression is for numbers:

let someSrt = "954  432 534  test abc test test test abc test test abc ";
        let stringNumber= someSrt.replace(/[0-9]/g, '');
        console.log(stringNumber);
        let stringText= someSrt.replace(/\D/g, ''); 
        console.log(stringText);

And in stringText I use the \D metacharacter (matches characters that are not numbers), which gives the result - numbers. Help me to understand.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alex, 2018-07-27
@MariaM0479

const someSrt = "954  432 534  test abc test test test abc test test abc ";

const words = someSrt.match(/([a-zA-Z]+)/g);
const numbers = someSrt.match(/(\d+)/g);

console.log(words); // ["test", "abc", "test", "test", "test", "abc", "test", "test", "abc"]
console.log(numbers); // ["954", "432", "534"]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question