0

I have a string like this:

AAAA 1 BBBB 2

I want to get all the number and return the result: 12

I tried \d but it just get the first number.

In conclusion, I want to get all the number from a string in order then combine it to make a new number.

Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
Keitaro Urashima
  • 841
  • 2
  • 9
  • 19

4 Answers4

3

You can extract out all number from your string using /\d+/g and then join the result to get your new number.

var result = 'AAAA 1 BBBB 2'.match(/\d+/g);
console.log(result.join(''));
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
2

I think your question can be satisfied by just removing all non numeric digits from the string. Then, you would be left with all numbers sandwiched togther.

var input = 'AAAA 1 BBBB 2';
input = input.replace(/[^0-9]/g, '');
console.log(input);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

Just check this code i hope it will fulfil your condition.

<script>
function myFunction() {
    var str = "AAAA 1 BBBB 2 CCCCC 6 asghj6adcgf 7"; 
    var patt1 = /\d+/g;
    var result = str.match(patt1);
    document.getElementById("demo").innerHTML = result;
}
</script>
0

You can use parenthesis for grouping (\d) and execute it multiple times until nothing is matched.

const regex = /(\d)/g,
    str = 'AAAA 1 BBBB 2'

let match
while(match = regex.exec(str)) {
    console.log(match[0])
}

result

1
2
Anurat Chapanond
  • 2,837
  • 3
  • 18
  • 31