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.
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.
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
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)
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)