lilo
lilo

Reputation: 195

Regex for hashtags is returning not correct number js

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

Answers (3)

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27192

  1. By using regex :

let text = "#Visit #test  #test2";

var count = (text.match(/#/g) || []).length;

console.log(count);

  1. By using String.split() method :

let text = "#Visit #test  #test2";

console.log(text.split('#').length - 1);

Upvotes: 0

Hangover Sound Sound
Hangover Sound Sound

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

Kanishk Anand
Kanishk Anand

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

Related Questions