Hi everyone, I’m new to the site and looking for an answer to this:
I want to match the word(s) that begin with a hashtag (#) on a given string. So far with a code like
var mystring = “Going to the #museum and then to the #gym”;
var mypattern = /(#)([a-zA-Z0-9])*/;
var myresult= mypattern.exec(mystring);
myresult contains
#museum,#,m
but:
I only want #museum
It’s not detecting #gym
The main reason for all this is, I want to get all text that is not a hashtag, so in this example I want to get
"Going to the "
"and then to the "
as two separate string. I thought using regular expressions would help me instead of searching the string for #.
By the way, # is called the ‘octothorp’ , from a word meaning eight-points.
Huh, I didn’t know that either, but Engrish has lots of names for that thing (number, pound, hash, (cross)hatch). For programming I’m going to keep calling it hash(mark) or shebang, depending on where it is, so people know what I’m talking about.
Came up with this match, which removes the trailing spaces. (If you’d want that???)
Can it be simplified?
var s=“Going to the #museum and then to the #gym”;
console.log (s.match(/(\w+ ?)+(?= #)|(#\w+)/g)); // ‘Going to the’,‘#museum’,‘and then to the’,‘#gym’
edit: forget it! it fails with “Going to the #museum and then to the #gym and then the pub”
Thank you indeed! I always thought regular expressions were very helpful, I guess I have to get me some tutorials and/or books. Any links recommended? I couldn’t find any on the Links/Tutorial thread.
This site is devoted to Regular expressions in javascript:
But try to find the Book, ‘Mastering Regular Expressions’,by Jeffrey EF Friedl,
published by O’Reilly. It’s a keeper, and covers other programming languages as well as javascript.
I have another question revolving on the same problem, but since it’s not related to regular expressions anymore, I will make a another post (if I can’t find the answer already in the forums).