Reputation: 195
I am trying to get the number of hashtags my case is for instagram, wanna make a validation but for some reason the number is appearing 2 instead of 3, I have 3 hashtags there! Do you guys know why?
let text = "#Visit #test #test2";
let pattern = /(^|\W)(#[a-z\d][\w-]*)/g;
let result = (text.match(pattern)).length;
console.log(result)
Upvotes: 0
Views: 36
Reputation: 27192
let text = "#Visit #test #test2";
var count = (text.match(/#/g) || []).length;
console.log(count);
let text = "#Visit #test #test2";
console.log(text.split('#').length - 1);
Upvotes: 0
Reputation: 192
You could do it in another way :
let text = "#Visit #test #test2"
let result= text.split("#").length - 1
console.log(result)
Here you split the text at the hash character, therefore the length will be the number of hashtags - 1.
Upvotes: 1
Reputation: 1702
You need to add the case-insensitive
modifier to your regex.
let text = "#Visit #test #test2";
let pattern = /(^|\W)(#[a-z\d][\w-]*)/ig; // Added 'i' as the modifier
let result = text.match(pattern).length;
console.log(result)
Upvotes: 3