对字符串使用IndexOf来挑选某些单词

using IndexOf on string to pick out certain words

本文关键字:挑选 单词 IndexOf 字符串      更新时间:2023-09-26

我正在尝试挑选用户输入的某些单词。基本上,下面是我网站上的人必须以完全相同的格式填写的表格。然而,唯一的区别是,"["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