安全地解析字符串,这样拆分就不会失败,或者如果失败,则至少返回0

parse the string safely so that the split must not fail or if fails it returns 0 atleast

本文关键字:失败 或者 如果 返回 字符串 安全 拆分      更新时间:2023-09-26

如何将此var a的解析简化为安全的方式,以便在var a不返回或失败的情况下。

  var a = "<span style='color:green;'>Speed (NORMAL): 3.36 MB/s</span>";
  a = a.split('>');
  a = a[1].split(' ');
  console.log(a[2]);

输出:

3.36 but its not safe parse cause the a could be empty or null or undefined 

目标是:

仅将值读取为:3.36

如果为空或a未定义/为null等,则应给出:0

您可以使用正则表达式:

var a = "<span style='color:green;'>Speed (NORMAL): 3.36 MB/s</span>";
a = parseFloat((a.match(/'d+('.'d+)?/) || '0')[0]);

.match()返回结果数组或null,因此,当正则表达式失败时:

(null || '0')[0] = '0'[0] = "0"

进一步阅读:

  • http://www.javascriptkit.com/javatutors/redev.shtml
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match