通过主题标签拆分字符串并使用 jQuery 保存到数组中? [英] Split string by hashtag and save into array with jQuery?
问题描述
我有一个包含一系列单词的字符串的 var,其中一些带有主题标签,例如:
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.
有什么特殊的方法可以做到这一点吗?是否有一些 ASCII 字符我打算用来识别这个?
Is there a special way of doing this? Is there some ASCII characters I am meant to use to identify this?
推荐答案
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(' ')
将带有空格的单词拆分为一个新数组
tagslistarr = words.split(' ')
splits words with spaces to from a new array
$.each() 循环遍历 tagslistarr
数组的每个值
$.each() loops through the each value of tagslistarr
array
if(tagslistarr[i].indexOf('#') == 0)
检查 #
是否在开头,如果这个条件是 true
将它添加到 arr
数组
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
这篇关于通过主题标签拆分字符串并使用 jQuery 保存到数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!