Split string on hashtag and save to array with jQuery?

I have a var that has a string with a series of words, some of which have hashtags, for example:

var words = "#hashtagged no hashtag #antoherhashtag"; 

I want to save each hashtagged word into an array, sort of like:

 var tagslistarr = words.split(' '); 

But I'm not sure how to get characters surrounded by both # and a space.

Is there a special way to do this? Are there any ASCII characters I should use to identify this?

+8
javascript jquery string arrays
source share
5 answers

Demo

 var words = "#hashtagged no hashtag #antoherhashtag"; var tagslistarr = words.split(' '); var arr=[]; $.each(tagslistarr,function(i,val){ if(tagslistarr[i].indexOf('#') == 0){ arr.push(tagslistarr[i]); } }); console.log(arr); 

tagslistarr = words.split(' ') splits words with spaces into a new array

$. each () goes through each value of the tagslistarr array

if(tagslistarr[i].indexOf('#') == 0) checks that # is at the beginning and, if this condition is true , it adds it to the arr array

+13
source share
 var words = "#hashtagged no hashtag #antoherhashtag"; var tagslistarr = words.match(/#\S+/g); //["#hashtagged", "#antoherhashtag"] 
+21
source share
 var tmplist = words.split(' '); var hashlist = []; var nonhashlist = []; for(var w in tmplist){ if(tmplist[ w ].indexOf('#') == 0) hashlist.push(tmplist[ w ]); else nonhashlist.push(tmplist[ w ]); } 
+2
source share
 var words = "#hashtagged no hashtag #antoherhashtag"; var tagslistarr = words.match(/(^|\s)#([^ ]*)/g); 
+1
source share

The regex is pretty simple using pure JavaScript:

 var str = "Lorem #ipsum dolor sit #amet"; var hashArray = (str.match(/#(\w+)/g)); console.log(hashArray); // => [ '#ipsum', '#amet' ] console.log(Array.isArray(hashArray)); // => true 

https://repl.it/C8GJ

If you need to handle diacritics:

 var str = "Loröm #ipsöm dolor sit #amöt"; var hashArray = (str.match(/#([A-zÀ-ÖØ-öø-ÿ]+)/g)); console.log(hashArray); // => [ '#ipsöm', '#amöt' ] console.log(Array.isArray(hashArray)); // => true 

https://repl.it/@ryanpcmcquen/QuickwittedParallelLemming

+1
source share

All Articles