【发布时间】:2015-04-28 15:43:57
【问题描述】:
我有这个字符串:
Hey I love #apple and #orange and also #banana
我想提取以# 符号开头的每个单词。
目前我正在用这段代码实现它:
var last = 0;
var n = 0;
var str = "Hey I love #apple and #orange and also #banana";
do{
n = str.indexOf("#", last);
if(n != -1){
//The code found the # char at position 'n'
last = n+1; //saving the last found position for next loop
//I'm using this to find the end of the word
var suffixArr = [' ', '#'];
var e = -1;
for(var i = 0; i < suffixArr.length;i++){
if(str.indexOf(suffixArr[i], n) != -1){
e = str.indexOf(suffixArr[i], n+1);
break;
}
}
if(e == -1){
//Here it could no find banana because there isn't any white space or # after
e = str.length; //this is the only possibility i've found
}
//extracting the word from the string
var word = str.substr(n+1, (e-1)-n);
}
}
while (n != -1);
我怎样才能找到仅以# 和a-Z characters 开头的单词。例如,如果我有#apple!,我应该能够提取apple
而且,正如我在代码中提到的,如果单词出现在字符串的末尾,我如何设法获取它
【问题讨论】:
标签: javascript regex string