我正在制作一个机器人,它扫描股票代码的字符串输入并返回当前价格。格式为 !{ticker} 例如 !AAPL
我目前拥有的功能是:
function getVals(comment){
let n = comment.indexOf("!")
//Check if value
if(n > 0){
let ticker = comment.substring(n +1, n+5);
//Then perform price check with ticker
} else{
console.log("error")
}
};
//Example comment
getVals("This if my first ticker !AAPL I also want to know !EA");
我遇到的问题是:
- 代码仅扫描“!”之后的 4 个字符。我不知道如何在空格之前结束
- 代码在第一个结果之后执行,而不是扫描剩余的代码。
任何帮助将不胜感激,提前致谢。
最佳答案
您应该使用Regexp来实现这一目标。
const str = 'This if my first ticker !AAPL I also want to know !EA';
const regexp = /![A-Z]+/g;
const result = str.match(regexp);
// Matches with '!' char
console.log(str.match(regexp));
// Removes '!' char
console.log(str.match(regexp).map((val)=>val.slice(1)));
关于javascript - 搜索字符串并返回特殊字符后的所有值的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48577738/