MeltingDog MeltingDog - 5 months ago 23
jQuery Question

Split string by hashtag and save into array with jQuery?

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

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


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

var tagslistarr = words.split(' ');


But I am unsure of how to get the characters surrounded by both the # and the space.

Is there a special way of doing this? Is there some ASCII characters I am meant to use to identify this?

Answer

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 to from a new array

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

if(tagslistarr[i].indexOf('#') == 0) checks is the # is in the beginning of the and if this condition is true it adds it into the arr array

Comments