-4

I have a string that looks like this: (5 Sonuç)

How do I extract number using filter function and not any string related function?

Filter function works on array but how do I make it work for a string I can't use replace or match functions.

Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
Amna Arshad
  • 767
  • 3
  • 10
  • 21
  • You can't use `filter()` on a string as it is an `Array.prototype` function. – fedesc Jul 26 '20 at 17:06
  • @fedesc of course you can call filter on a string (see my answer below) – Mehdi Belbal Jul 26 '20 at 17:20
  • @MehdiBelbal You are converting the string to an array in order for `filter` to work. which is like `split()` but it is a nice way of getting the desired result – fedesc Jul 26 '20 at 17:26
  • 1
    @fedesc a string is actually an array of character even in google v8 engine so it can be downcasted to its original form without spliting it in an actual explicite Array of char, which is a little more work for the engine – Mehdi Belbal Jul 26 '20 at 17:32

3 Answers3

2

You can use the spread operator:

const str = "5 Sonuç"
[...str].filter(c => typeof c === 'number' && isFinite(c));

And if, you faced the error:

Type 'IterableIterator' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.

Instead of

[...str]

you can rely on

Array.from(str)

More on downlevelIteration

aloisdg
  • 22,270
  • 6
  • 85
  • 105
0

You can use filter on a string by calling Array.prototype.filter.call with your string as the "this" argument and the filter function as second arguments.

example :

var str = "5 dfkdf9 eofh"
let res = Array.prototype.filter.call(str, n=>!isNaN(parseInt(n)))

console.log(res)
Mehdi Belbal
  • 523
  • 3
  • 7
0

Use the split() function to return an array then use the filter() function to take out the non-numbers in the array. You can then convert back to a string (if needed) using string related functions

let myString = "5 Sonuç"

let myNum = myString.split("").filter(e => !isNaN(e));
console.log(myNum)