【发布时间】:2015-11-05 14:34:02
【问题描述】:
我正在尝试在 Javascript 学习网站上完成一个练习。
说明是:
输入:单词字符串,其中一些单词可能包含井号/井号#。
输出:以井号/井号 # 为前缀但不包含井号/井号 # 的字符串数组。
单独的磅号不算数,例如:字符串“#”将返回一个空数组。
- 如果一个词前面有多个主题标签,则只计算最后一个主题标签(例如,“##alot”将返回 [“alot”])
- 标签不能位于单词的中间(例如,“in#line hashtag”返回一个空数组)
- 标签必须在字母字符之前(例如“#120398”或“#?”无效)
我的努力是这样的:
function getHashtags(post) {
return /#(\w+)/.exec(post)
}
但结果是这样的:
String Input: Hello #world
Outpu t: [ '#world', 'world', index: 6, input: 'Hello #world' ]
String Input: #lol #sorryNotSorry #heya #coolbeans
Output: [ '#lol','lol', index: 0, input: '#lol #sorryNotSorry #heya #coolbeans']
String Input: # # # #
Output: null
String Input: this is an in#line hash
Output: [ '#line', 'line', index: 13, input: 'this is an in#line hash' ]
String Input: too ##many tags
Output: [ '#many', 'many', index: 5, input: 'too ##many tags' ]
String Input: invalid chars #$? #;wha
Output: null
String Input: "" //empty string
null
String Input: #blue#red#yellow#green
Output:[ '#blue', 'blue', index: 0, input: '#blue#red#yellow#green' ]
我认为我需要回溯功能,但我知道 Javascript 不支持它并且我无法找到解决方法!有人可以帮忙吗?
【问题讨论】:
标签: javascript arrays regex string