For your specific example, @Steve's answer will work just fine, because you're testing against a specific condition at the end of your string. If, however, you want to test against more complex strings, you can also consider using Regular Expressions (also known as RegEx). That Mozilla documentation has an excellent tutorial on how to use regular expressions for JavaScript.
To create a regex pattern and use it to test your string, you can do something like the following:
const regex = /:\s*$/;
// All three will output 'true'
console.log(regex.test('foo:'));
console.log(regex.test('foo: '));
console.log(regex.test('foo: '));
// All three will output 'false'
console.log(regex.test('foo'));
console.log(regex.test(':foo'));
console.log(regex.test(': foo'));
...Where the regular expression /:\s*$/
can be interpreted like so:
/ Start of regex pattern
: Match a literal colon (:)
\s Right afterward, match a whitespace character
* Match zero or more of the preceding characters (the space character)
$ Match at the end of the string
/ End of regex pattern
You can use Regexr.com to do live testing for different regex patterns that you come up with, and you can input sample text into the text box to see if your pattern matches.
Regular expressions are a powerful tool. There are some cases where you want to use them and other cases where it's overkill. For your particular example, just using a simple .endsWith()
is more straightforward and most likely preferred. If you need to do complex pattern matching where JavaScript functions won't cut it, regular expressions can do the trick. It's worth reading up about and another good tool to put in the toolbox.