--- tags: JavaScript, Codewars,7kyu Filter the number title: Codewars - 7kyu Filter the number --- ###### tags: `Codewars` 、`7kyu Filter the number`、`JavaScript` ###### *date: 2022 / 10/ 27* # 💪 7kyu Filter the number **思考模式:** 把傳入字串列中的字串部分過濾掉並回傳數字型別。 **解法一** 1. 使用 **split('')** 將字串轉陣列在使用 **filter()** 下篩選條件 2. 運用 **isisNaN** 內含 Number() 轉數字的資料轉型方法把 false 結果,使用 !(not) 轉為 true 的結果回傳出來。 3. 最後使用**Number()** 將字串轉為數字型別並回傳出來。 ```jsx var filterString = function (value) { const newNum = value.split('').filter((num) => { return !isNaN(num); }).join(''); return Number(newNum); }; console.log(filterString("123"));//123 console.log(filterString("a1b2c3"));//123 console.log(filterString("aa1bb2cc3dd")); //123 ``` **解法二** 使用字串方法 [replace()](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/String/replace) ```jsx var filterString = function(value) { return parseInt(value.replace(/[^\d]/g, "")) }; console.log(filterString("123"));//123 console.log(filterString("a1b2c3"));//123 console.log(filterString("aa1bb2cc3dd")); //123 ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up