检查字符串是否包含javascript中的字符序列和未知变量

Checking if a string contains character sequence and unknown variable in javascript?

本文关键字:未知 变量 字符 是否 字符串 包含 javascript 检查      更新时间:2023-09-26

是否可以检查javascript字符串是否包含指定的一系列字符和其中的未知字符。例如:

var secondValue = 9;
var testString = "the result is 8 and " + secondValue + " as shown above";
var stringToTestAgainst1 = "the result is * and " + secondValue  + " as show above";
var stringToTestAgainst2 = "the result is * as show above";

我如何测试这些,以便在比较testString和第一个值时返回true。但是当它与第二个比较时是假的?

您可以使用正则表达式:

/the result is 'd+ as shown above/.test('the result is 8 as shown above')
// => true

参见MDN的RegExp docs。

'd+检查是否存在一个或多个数字。

编辑

您可以检查许多东西的存在,如'd用于数字,'w用于任何字母数字字符,等等。