Skip to main content
 首页 » 编程设计

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

2025年05月04日20del

我已经用 Python 编写了一些代码,但我必须用 JavaScript(用于 Google Apps 脚本)编写。我会说我在 JS 方面很糟糕并且似乎无法复制我在 Python 中所做的事情。 基本上,我有一个字符串,它可能有也可能没有“/”或“-”,如果有,我希望它用“”替换与 2 个特定数组匹配的所有子字符串。

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

 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”。我想测试字符串是否有“/”或“-”,如果有,用“”替换“Monday”和“October”。最终结果将是“,2nd 23:59”

抱歉,如果这看起来微不足道,但我真的找不到办法,并且已经搜索过类似的解决方案但无济于事。

请您参考如下方法:

首先,我们使用 string.protoype.includes 检查字符串是否包含“/”或“-”然后创建一个数组,其中包含您要替换的内容。对于该数组上的每个字符串并一个一个地替换字符串。

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