javascript 如何在没有正则表达式的情况下从字符串中获取数字

rdrgkggo  于 2023-08-02  发布在  Java
关注(0)|答案(2)|浏览(120)

在不使用regex的情况下,有没有一种方法可以在JavaScript中从字符串中获取number?

例如,如果输入是"id is 12345",那么我希望输出中有12345数字。
我知道很多正则表达式的解决方案,但我正在寻找一个非正则表达式整洁的解决方案。

nhaq1z21

nhaq1z211#

迭代字符并检查它们是否在一组数字中:

  1. const str = 'id is 12345 or 54321';
  2. const set = new Set([...'0123456789']);
  3. const nums = [];
  4. let start = -1;
  5. for (let i = 0; i <= str.length; i++) {
  6. const c = str[i];
  7. if (set.has(c)) {
  8. if(start === -1 ){
  9. start = i;
  10. }
  11. } else {
  12. start > -1 && nums.push(+str.slice(start, i));
  13. start = -1;
  14. }
  15. }
  16. console.log(nums);

字符串
如果你想要最快的解决方案,请使用Unemitted的c >= '0' && c <= '9'String::slice()


的数据

  1. <script benchmark data-count="1">
  2. const str = "abc def 12345 xyz 987".repeat(1000000);
  3. // @benchmark Unmitigated
  4. {
  5. let res = [], curr = '';
  6. for (const c of str + ' ') {
  7. if (c >= '0' && c <= '9') // add || c === '-' (to handle negatives)
  8. curr += c;
  9. else if (curr)
  10. res.push(+curr), curr = '';
  11. // use BigInt(curr) to handle larger numbers
  12. }
  13. res
  14. }
  15. // @benchmark Alexander
  16. {
  17. const set = new Set([...'0123456789']);
  18. const nums = [];
  19. let start = -1;
  20. for (let i = 0; i <= str.length; i++) {
  21. const c = str[i];
  22. if (set.has(c)) {
  23. if(start === -1 ){
  24. start = i;
  25. }
  26. } else {
  27. start > -1 && nums.push(+str.slice(start, i));
  28. start = -1;
  29. }
  30. }
  31. nums
  32. }
  33. // @benchmark Unmitigated + String::slice()
  34. {
  35. let res = [], start = -1;
  36. for (let i = 0; i <= str.length; i++) {
  37. const c = str[i];
  38. if (c >= '0' && c <= '9') {
  39. if(start === -1 ){
  40. start = i;
  41. }
  42. } else {
  43. start > -1 && res.push(+str.slice(start, i));
  44. start = -1;
  45. }
  46. }
  47. res
  48. }
  49. </script>
  50. <script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>

展开查看全部
olmpazwi

olmpazwi2#

您可以循环遍历所有字符,并从连续的数字中构建数字。
这里有一个解决方案,适用于多个数字(仅使用字符0-9形成)。

  1. const str = "abc def 12345 xyz 987";
  2. let res = [], curr = '';
  3. for (const c of str + ' ') {
  4. if (c >= '0' && c <= '9') // add || c === '-' (to handle negatives)
  5. curr += c;
  6. else if (curr)
  7. res.push(+curr), curr = '';
  8. // use BigInt(curr) to handle larger numbers
  9. }
  10. console.log(res);

字符串

相关问题