user3024235 user3024235 - 1 month ago 10
Javascript Question

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

Is it possible to check if a javascript string contains a specified series of characters and an unknown character in between. For example:

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";


How can I test these in a way so that it returns true when comparing the testString to the first value. But false when comparing it to the second?

Answer

You can use a regular expression:

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

See MDN's RegExp docs.

\d+ checks for the presence of one or more digits.

Edit

You can check for the presence of many things, like \d for digit, \w for any alphanumeric character, etc. The reference above provides many examples.