Nodejs index的具体编号

时间:2018-11-20 14:20:50

标签: javascript indexof

此代码:

var t = "test 55";
t.indexOf("5") !== -1

输出true,

但是此代码:

var t = "test 55";
t.indexOf("5") !== -1

也输出true,

当它的数字完全相同时,如何使它仅输出true?

var t = "test 55";
t.indexOf("5") !== -1

输出:false,

var t = "test 5";
t.indexOf("5") !== -1

输出为真。


2 个答案:

答案 0 :(得分:0)

双引号或单引号中的值被JavaScript视为String类型。因此,indexOf的实际作用是在字符串(“ 55”)内寻找子字符串(“ 5”)。

我不确定为什么要尝试使用indexOf来比较数字,难道不能只使用:

var t = "55";
t == 5 //false
t == "55" // true
t == "5" // false

请注意,我使用==而不是===。使用==会将值转换为相同的类型(如果t =“ 55”转换为字符串)并进行比较。

编辑

由于op阐明了t值同时包含数字和字母,因此为了进行比较,需要附加的逻辑。

  1. 从字符串中提取数字。
  2. 将其与提供的数字进行比较。

您可以使用以下功能来实现它:

function compare(number, stringWithNumber) {
  // slice string with number to get a string starting with a number
  const stringStartingWithNumber = stringWithNumber.slice(stringWithNumber.search(/\d/));
  return parseFloat(stringStartingWithNumber) == number; // parseFloat removes the rest of the string and parses found number as float
}

然后:

compare("5", "55") // false
compare("5", "5") // true
compare("5", "sometext 55") // false
compare("5", "sometext 5") // true

请注意,该函数只会将提供的数字与在stringWithNumber参数中找到的第一个数字进行比较。

答案 1 :(得分:0)

.indexOf()不适合您要执行的操作。您可以使用.search()(这个问题的原始版本带有标签的情况也是如此)。
您没有明确指出5.5应该产生什么,所以我将给出两个表达式-第一个更简单的/\b5\b/与之匹配,而第二个更复杂的/(^|[^.])\b5\b(?!\.)/则不。在5之前和之后,小数点的排除都是不对称的,因为我避免使用后置断言,只有ECMAScript 2018以后才支持。

t = ["5", "test 5", "test 55", "test 5.5"]
console.log('with regex '+/\b5\b/)
for (i in t)
  console.log(t[i], t[i].search(/\b5\b/) !== -1)
console.log('with regex '+/(^|[^.])\b5\b(?!\.)/)
for (i in t)
  console.log(t[i], t[i].search(/(^|[^.])\b5\b(?!\.)/) !== -1)