【问题标题】:Compare two string using JavaScript and substitute an ampersand for the word and使用 JavaScript 比较两个字符串,并用 & 号替换单词和
【发布时间】:2020-08-29 19:25:45
【问题描述】:

我需要比较来自两个不同数据源的两个字符串。在一个系统中,他们可以输入单词 and,而在另一个系统中,它可能是 &,或者相反,或者它们可能是相同的。

目前我正在使用

            if (thisAffiliation.search(new RegExp(department, "i")) > 0) {   
            validatedDepartment = true
            }

            if (thisAffiliation.search(new RegExp(department.replace('and','&'), "i")) > 0) {   
            validatedDepartment = true
             }

            if (thisAffiliation.search(new RegExp(department.replace('&','and'), "i")) > 0) {   
            validatedDepartment = true
             }

有没有办法可以将三个 if 语句合二为一?

补充资料:

如果满足以下条件,我需要验证部门 = true:

        Smith and Jones   =   Smith & Jones
        Smith and Jones   =   Smith and Jones

如果是的话

        Smith & Jones    =  Smith & Jones
        Smith & Jones    = Smith and Jones

我无法控制 and 或 & 出现在哪里

【问题讨论】:

  • ...或者您可以创建一个正则表达式来处理所有三个搜索。
  • 如果 (thisAffiliation.search(new RegExp(department, "i")) > 0 || thisAffiliation.search(new RegExp(department.replace('and','&'), "i")) > 0 || thisAffiliation.search(new RegExp(department.replace('&','and'), "i")) > 0) { validDepartment = true } 但为了便于阅读,我认为原件是更好
  • 而且我不知道如何使用 RegEx,所以它不认为它是一个循环 - 改变 & for 和再回来。如果降级问题的人可以提出一个智能的解决方案,我将不胜感激
  • 所以你想接受一个是另一个的子字符串,但不相等?

标签: javascript regex vue.js


【解决方案1】:

您不必为此从输入字符串创建正则表达式(除非源值表示一个正则表达式)。

要在“and”和“&”之间没有区别,只需在一个方向进行转换,在 both 字符串中,并且总是这样做。使用函数将相同的逻辑应用于两个字符串:

const clean = (s) => s.replace(/&/g, "and").toLowerCase();

if (clean(thisAffiliation) === clean(department)) {   
    validatedDepartment = true;
}

如果没有其他条件影响validatedDepartment的值,那么你可以只分配布尔条件:

let validatedDepartment = clean(thisAffiliation) === clean(department);

【讨论】:

  • 完美——正是我想要的。将两者转换为同一方向是我希望但无法想象的。谢谢
猜你喜欢
  • 1970-01-01
  • 2019-04-27
  • 2021-12-20
  • 1970-01-01
  • 2015-02-25
  • 1970-01-01
  • 1970-01-01
  • 2016-10-08
  • 1970-01-01
相关资源
最近更新 更多