To check if a string is a valid hashtag, we can use a regex expression to match for a string that starts with a #
(hash symbol) in JavaScript.
TL;DR
// Regular expression to check if string is a hashtag
const regexExp = /^#[^ !@#$%^&*(),.?":{}|<>]*$/gi;
// String with hashtag
const str = "#helloWorld";
regexExp.test(str); // true
This is the regex expression for matching almost all the test cases for a valid hashtag in JavaScript.
// Regular expression to check if string is a hashtag
const regexExp = /^#[^ !@#$%^&*(),.?":{}|<>]*$/gi;
Now let's write a string with valid hashtag like this,
// Regular expression to check if string is a hashtag
const regexExp = /^#[^ !@#$%^&*(),.?":{}|<>]*$/gi;
// String with hashtag
const str = "#helloWorld";
Now to test the string, we can use the test()
method available in the regular expression we defined. It can be done like this,
// Regular expression to check if string is a hashtag
const regexExp = /^#[^ !@#$%^&*(),.?":{}|<>]*$/gi;
// String with hashtag
const str = "#helloWorld";
regexExp.test(str); // true
- The
test()
method will accept astring
type as an argument to test for a match. - The method will return boolean
true
if there is a match using the regular expression andfalse
if not.
See the above example live in JSBin.
If you want this as a utility function which you can reuse, here it is,
/* Check if string is a valid Hashtag */
function checkIfValidHashtag(str) {
// Regular expression to check if string is a hashtag
const regexExp = /^#[^ !@#$%^&*(),.?":{}|<>]*$/gi;
return regexExp.test(str);
}
// Use the function
checkIfValidHashtag("#helloWorld"); // true
checkIfValidHashtag("#%hello98123!"); // false
That's all! 😃