使用JavaScript获取字符串中的第一个数字

使用javascript编写了一个示例代码,用于获取字符串中的第一个数字。用“search”检索在正则表达式中找到第一个数字的位置。

检索找到的第一个数字

要检索字符串中找到的第一个数字,请检索search中找到的第一个位置,并为字符串指定索引编号。

const str = 'hello973world89';

const index = str.search(/[0-9]/);

// 找到数字的第一个位置
console.log(index); // 5

const first = Number(str[index]);

console.log(first); // 9

在转换数字之前进行条件判断,如果不存在数字则返回“-1”。

const str = 'hello';

const index = str.search(/[0-9]/);

// 找到数字的第一个位置
console.log(index); // -1

if (index !== -1) {
  const first = Number(str[index]);
  console.log(first); 
}

如果包含全角数字,请修改正则表达式,将全角数字更改为半角数字。

const str = 'hello8723world89';

const index = str.search(/[0-90-9]/);

// 找到数字的第一个位置
console.log(index); // 5

// 将全角更改为半角并进行量化
const first = Number(str[index].replace(/[0-9]/g, function(v) {
        return String.fromCharCode(v.charCodeAt(0) - 0xFEE0);
    }));

console.log(first); // 8

使用JavaScript获取字符串中的第一个数字  第1张

示例代码

单击“运行”按钮在表单中输入的值中找到第一个数字。

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>使用JavaScript获取字符串中的第一个数字</title>
  <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.2/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>

  <div class="container text-center" style="margin-top:100px">

    <h2><span class="badge bg-danger">结果</span></h2>

    <form>
      <div class="form-group">        
        <input type="text" id="setData">
      </div>
    </form>

    <button type="button" onclick="seachFirstNum()" class="btn btn-danger">
      运行
    </button>

  </div>

  <script>    

    const seachFirstNum = () => {

      let obj = document.getElementsByClassName("badge")[0];

      obj.textContent = Number(setData.value[setData.value.search(/[0-9]/)]);

    }

  </script>
</body>

</html>

运行结果

使用JavaScript获取字符串中的第一个数字  第2张

本文来源:词雅网

本文地址:https://www.ciyawang.com/javascript-search-number.html

本文使用「 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 」许可协议授权,转载或使用请署名并注明出处。

相关推荐