如果子字符串是数组的一部分,则替换该子字符串

2024-09-26 18:15:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经用Python编写了一些代码,但是我必须用JavaScript(对于googleapps脚本)来编写。我会说我在JS方面相当差劲,似乎无法复制我在Python中所做的工作。 基本上,我有一个字符串,它可能有或没有“/”或“-”,如果有,我希望它将所有匹配2个特定数组的子字符串替换为“”。你知道吗

(对于上下文,whitelistdias和whitelistmes是两个数组,其中包含多个单词)

 var whitelistdias = ["terça-feira", "quarta-feira",
                     "quinta-feira", "sexta-feira", "sábado", "domingo",
                     "segunda", "terça", "quarta", "quinta", "sexta", "sabado",
                     "terca"];

  var whitelistmes = ["janeiro", "fevereiro", "março", "abril", "maio", "junho",
                    "julho", "agosto", "setembro", "outubro", "novembro",
                    "dezembro", "jan", "fev", "mar", "abr", "mai", "jun",
                    "jul", "ago", "set", "out", "nov", "dez"];

我使用的Python代码发布在下面:

    idk = str(idk)
    if "/" in idk or "-" in idk:
        for i in whitelistmes:
            if i in idk:
                mes = i
                idk = idk.replace(i, "")

        for i in whitelistdias:
            if i in idk:
                idk = str(idk)
                idk = idk.replace(i, "")

示例:

基本上,假设字符串是“10月2日,星期一,23:59”。我想测试字符串是否有“/”或“-”,如果有,用“”替换“星期一”和“十月”。最终的结果是“第二天23:59”

抱歉,如果这似乎微不足道,但我真的找不到一个方法来做这件事,并已寻找类似的解决方案,但没有任何结果。你知道吗


Tags: 字符串代码inifvar数组marter
3条回答

如果有人对regex的简短解决方案感兴趣:

let idk = "Monday, 2nd - October, 23:59"; let whitelist = ["Monday", "October"]; let regstr = new RegExp(whitelist.join('|'),'g'); // just to show the replace code and ignore '/' and '-' check idk = idk.replace(regstr,''); console.log(idk);

首先,我们使用^{}检查字符串是否包含“/”或“-”,然后创建一个包含要替换的内容的数组。对数组中的每一个进行替换,并逐个替换字符串。你知道吗

let str = "Monday, 2nd October, 23:59 -" // it contains "-" let thingsToReplace = ["Monday", "October"] if (str.includes("/") || str.includes("-")) { // || this means that if any of them is true then returns true thingsToReplace.forEach((strs) => { // for each the array and replace every string str = str.replace(strs, ""); // replace the string via string.replace(what to replace, and with what) }) } console.log(str) // log it so we can see

两件事:

  • 对于字符串中是否存在子字符串,可以使用indexOf()includes()
  • 对于迭代,使用for loopforEach
  • 对于替换,函数是相同的:replace()

以下是运行代码:

idk = "Monday, 2nd - October, 23:59"; whitelistmes = ["January", "October"]; whitelistdias = ["Tuesday", "Monday"]; if (idk.indexOf("/") != -1 || idk.indexOf("-") != -1) { for (i in whitelistmes) { if (idk.indexOf(whitelistmes[i]) != -1) { //mes = i idk = idk.replace(whitelistmes[i], ""); } } for (i in whitelistdias) { if (idk.indexOf(whitelistdias[i]) != -1) { //idk = str(idk) idk = idk.replace(whitelistdias[i], ""); } } } console.log(idk);

上面的版本复制了您的代码。下面是更好的版本:

请注意,您也可以将whitelistmeswhitelistdias合并为一个,因为所采取的操作对两者都是相同的。你知道吗

相关问题 更多 >

    热门问题