Javascript:从字符串中的特定字符开始提取单词 [英] Javascript : Extract words starting with specific character in a string
本文介绍了Javascript:从字符串中的特定字符开始提取单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个字符串:
Hey I love #apple and #orange and also #banana
我想提取以#
开头的每个单词符号。
I would like to extract every words that start with the #
symbol.
目前我正在用以下代码实现它:
Currently I'm achieving it with this code :
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);
如何找到以#开头并带有 aZ字符的单词
仅限。例如,如果我有 #apple!
我应该能够提取 apple
而且,因为我在代码中提到,如果它出现在字符串的末尾,我如何设法得到这个词
How can I manage to find words starting with # and with a-Z characters
only. If for example I have #apple!
i should be able to extract apple
And also, as I mentionned in the code, how do I manage to get the word if it appears at the end of the string
推荐答案
(?:^|[ ])#([a-zA-Z]+)
试试这个。抓住捕获。参见演示。
Try this.Grab the capture.See demo.
https://regex101.com/r/wU7sQ0/18
var re = /(?:^|[ ])#([a-zA-Z]+)/gm;
var str = 'Hey I love #apple and #orange and #apple!@ also #banana';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
这篇关于Javascript:从字符串中的特定字符开始提取单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文