【问题标题】:How can I remove all characters after a specified word and before a period in a string using javascript?如何使用javascript删除字符串中指定单词之后和句点之前的所有字符?
【发布时间】:2020-02-07 21:45:10
【问题描述】:

我有这个字符串:

1_plex_light-blue-striped_imagegroup.jpg?v=1581100432

有时看起来像这样:

1_plex_light-blue-striped_imagegroup_d6f347cf-1440-45ef-955d-144ge18d0a00.jpg?v=1581100432

字符串由不同的位组成,我的代码使用这些位来帮助决定在何处以及何时显示图像。

  • 1(按图片组排序)
  • plex(产品名称)
  • 浅蓝色条纹(彩色)
  • 图像组(让我的代码知道图像是组的一部分

代码:

此代码位于单击颜色框时触发的函数内。我传入被单击的框的颜色,后跟单词“_imagegroup”,并使用字符串帮助从我开始使用的图像组中过滤具有所选颜色的图像。

    var imagesArray = makeProductImagesArray();

    function filterImageByColourAndGroupType(image) {
          return image.masterImagePath.includes(`${colour}_imageset.`);
    }

    var filteredArray = imagesArray.filter(filterImageByColourAndGroupType);

    filteredArray.sort((a, b) => a.masterImagePath.replace(/\D/g,'').localeCompare(b.masterImagePath.replace(/\D/g,'')));

问题:

有时匹配会失败,因为像“d6f347cf-1440-45ef-955d-144ge18d0a00”这样的随机字符串被添加到图像路径中。

如何确保我的过滤器只返回与此格式匹配的图像:

light-blue-striped_imagegroup.

过滤器需要认为在“imagegroup”之后添加的字符串不存在。它会看到:

1_plex_light-blue-striped_imagegroup.jpg?v=1581100432

完全忽略:

_d6f347cf-1440-45ef-955d-144ge18d0a00

提前致谢

【问题讨论】:

  • 你能给我们看看 filterImageByFlavourAndSetType 的代码吗?您的代码 sn-p 只有 filterImageByColourAndGroupType 的代码。
  • 抱歉,应该是:filterImageByColourAndGroupType。我已经编辑了我的代码。

标签: javascript jquery regex


【解决方案1】:

您可以使用Lookbehind assertion 来匹配图像组前面的字符:

const str = '1_plex_light-blue-striped_imagegroup_d6f347cf-1440-45ef-955d-144ge18d0a00.jpg?v=1581100432';
console.log(str);
const regex = "/(?<=imagegroup).*\./"

const newStr = str.replace(regex, '.');
console.log(newStr)

编辑: Lookbehind assertion 的形式为 (?&lt;=y)x,仅当“x”前面有“y”时才匹配“x”,举个简单的例子:

const str = 'matchNOT but matchTHIS';

//this will look for anything containing the word 'match', 
//but only if it's preceded by the word 'but'; so 'match' before 'but' will be ignored
// and 'match' after 'but' will be captured.
const newStr = str.match(/(?<=but).*match.*/);

console.log(newStr)

【讨论】:

  • 给出可比较的字符串示例,以便我了解要保留和删除的内容
【解决方案2】:

您可以使用正则表达式。这样的事情会起作用:

function filterImageByColourAndGroupType(image) {
  const regex = new RegExp(`[0-9]+_.*_${colour}_imagegroup[_.*]?`);
  return image.masterImagePath.match(regex) != null;
}

这将匹配1_plex_light-blue-striped_imagegroup.jpg?v=15811004321_plex_light-blue-striped_imagegroup_d6f347cf-1440-45ef-955d-144ge18d0a00.jpg?v=1581100432

您可能需要根据值的特定约束(我不知道,只是在这里猜测)稍微调整确切的正则表达式,但这应该可以帮助您入门。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-20
    • 2020-07-29
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-28
    相关资源
    最近更新 更多