如何确定两个字符串是否在JavaScript中包含相同的单词?

时间:2018-04-08 14:11:37

标签: javascript arrays node.js ecmascript-6 exif

所以,我最感兴趣的是看谁有这个问题的聪明解决方案。它可能会归结为split和一些比较循环。

问题:我正在组合exif数据的多个字段来为图像创建标题。问题是这些exif数据的内容范围很广。

尼康的例子:

exifData.Make = "NIKON CORPORATION"
exifData.Model = "NIKON D90"

摩托罗拉手机示例:

exifData.Make = "Motorola"
exifData.Model = "XT1032"

在摩托罗拉的情况下,我只使用MakeModel的组合。

然而,在尼康的情况下,有重复,所以我想忽略Make并在这种情况下优先考虑Model

3 个答案:

答案 0 :(得分:2)

Make转换为包含一组字词的RegExp,如果Model包含匹配项,则转换为test。如果它包含,请选择Model,如果不包含,请结合MakeModel

const getTitle = ({ Make, Model }) =>
  new RegExp('\\b' + Make.replace(/\s+/g, '|') + '\\b', 'i')
    .test(Model) ? Model : `${Make} ${Model}`;

console.log(getTitle({ Make: "Motorola", Model: "XT1032" }));
console.log(getTitle({ Make: "NIKON CORPORATION", Model: "NIKON D90" }));

答案 1 :(得分:0)

您可以使用Make拆分Model字符串并检查includes()中的第一个令牌:

let exifData1 = {Make: "NIKON CORPORATION", Model: "NIKON D90"},
    exifData2 = {Make: "Motorola", Model: "XT1032"};

function getName(o) {
  return !o.Model.includes(o.Make.split(" ")[0]) ? o.Make + " " + o.Model : o.Model;
}

console.log(getName(exifData1));
console.log(getName(exifData2));

答案 2 :(得分:0)



let exifData = {};

exifData.Make = "NIKON CORPORATION"
exifData.Model = "NIKON D90"

let elems = {},
  repeats = {};

let make = exifData.Make.toLowerCase().split(" ").forEach(data => {
  elems[data] = true;
});

let model = exifData.Model.toLowerCase().split(" ").forEach(data => {
  if(elems[data]) repeats[data] = true;
});