对字符串使用IndexOf来挑选某些单词
using IndexOf on string to pick out certain words
我正在尝试挑选用户输入的某些单词。基本上,下面是我网站上的人必须以完全相同的格式填写的表格。然而,唯一的区别是,"["answers"]"中的所有内容都是他们唯一可以改变的东西
然而,他们是否在文本开始之前和文本开始之后添加空格(意思是在"贸易伙伴"之前和"通过发送此消息…"句子之后)
Trade Partner: [OMeGaXX]
My Items: ["https://www.roblox.com/The-Classic-ROBLOX-Fedora-item?id=1029025"]
Their Items: ["https://www.roblox.com/The-Classic-ROBLOX-Fedora-item?id=1029025"]
By sending this message I agree that I have not been bribed or blackmailed to send this and I am completely willing to take part in this trade.
我需要帮助,试着找出方块引号中的所有内容。例如,括号中的名称"OMeGaXX"代表贸易伙伴。"我的项目"中也可以有多个项目,它们用逗号分隔:这与"他们的项目"完全相同。我想知道如何将"我的物品"answers"他们的物品"中的所有URL添加到URL中。
此外,最后一句必须始终在谢谢
要查找括号之间的内容,可以使用正则表达式。假设消息保存在变量msg
中,那么我们可以使用创建一个匹配数组
var data = msg.match(/'[.+?']/gi);
这基本上是在字符串中搜索任何与[anytexthere]
匹配的模式,并将它们全部放在一个数组中。
不过,这些元素仍在括号中,因此使用以下代码删除字符串的第一个和最后一个字符:
data[1].substring(1,data[1].length-1);
要检查最后一个句子是否在中,可以检查字符串的最后143个字符(在本例中)是否等于该句子。为此,请使用
var lastSentence = msg.substring(-143,0);
if(lastSentence === "By sending this message I agree that I have not been bribed or blackmailed to send this and I am completely willing to take part in this trade.") {
//Yay, the last sentence is there!
}
可能不想使用indexOf;使用正则表达式:
var str = `
Trade Partner: [OMeGaXX] My Items: ["https://www.roblox.com/The-Classic-ROBLOX-Fedora-item?id=1029025"] Their Items: ["https://www.roblox.com/The-Classic-ROBLOX-Fedora-item?id=1029025"]
`,
regex = /'[([^']]*)']/g,
tradePartner = str.match(regex)[1],
myItems = str.match(regex)[1].split(","),
theirItems = str.match(regex)[1].split(",");
索引1处匹配的所有内容都将是正则表达式中的组(括号之间的所有内容)。
在您的代码中,您应该检查内容是否为空:(match = str.match(regex)) ? match[1] : null;
您可能需要研究regex。
var msg = 'Trade Partner: [OMeGaXX] 'nMy Items: ["https://www.roblox.com/The-Classic-ROBLOX-Fedora-item?id=1029025"] 'nTheir Items: ["https://www.roblox.com/The-Classic-ROBLOX-Fedora-item?id=1029025"]'n'nBy sending this message I agree that I have not been bribed or blackmailed to send this and I am completely willing to take part in this trade."';
var matched = msg.match(/'[.*']/g);
$(function(){
$("span").html(matched.join("<br>"));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Matched: <span></span>
Regex解释:
/
'[ match the exact character [
.* match everything
'] match the exact character ]
/g match multiple occurrences in the string
相关文章:
- 当鼠标悬停在文本中的单词上时显示警报
- 匹配一个单词,其中候选人可以跨越顺序组(跨度)
- 如何使用jquery强制一个单词更改大小写等以保留品牌
- 拆分单词jquery
- 如何让程序检查所选单词中是否有按键
- 如何在悬停时流畅地更改单词
- EmberJS中支持单字母单词模型
- 字母计数:返回重复字母数最多的第一个单词
- 如何在Javascript中从字符串中提取某些单词
- 如何创建一个“;表单弹出框“;在chrome中右键单击时位于突出显示的单词上方
- 在javascript中查找单词
- 使用jQuery检查提交时添加到句子中的单词
- 如何在PHP中获取特定的字符串单词
- 停止较大单词的重叠
- 如何在没有单词的情况下从命令行运行Node.js程序'节点'
- 用于匹配不带字符的单词的正则表达式
- 从输入值中删除最后一个单词
- 如何使用Javascript在给定的句子中找到大写单词并在其前面添加一个字符
- 如何将单词(包括单词)与连字符匹配
- 对字符串使用IndexOf来挑选某些单词