In this article, you’ll learn how to check if the string is a valid hashtag in javascript. We used the regular expression to check whether a string is valid that starts with a # (hash symbol) in JavaScript.
This regex expression we used 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 to test the string as a valid hashtag, we can use the test()
method available in the regular expression as we defined. It can be done like this in the below example,
// Regular expression to check if string is a hashtag
const regexExp = /^#[^ !@#$%^&*(),.?":{}|<>]*$/gi;
// String with hashtag
const str = "#tutorialsrack";
console.log(regexExp.test(str)); // true
The test()
method will accept a string type as an argument to test for a matching regex expression. This method will return boolean true
if there is a match using the regular expression and if there is no match then it will return false
.
If you want this as a utility function that 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
console.log(checkIfValidHashtag("#tutorialsrack")); // true
console.log(checkIfValidHashtag("#%tutorialsrack!")); // false
I hope this article will help you to understand how to check if the string is a valid hashtag in javascript.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments