首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何创建与两个键的图像alt文本匹配的Regex函数

如何创建与两个键的图像alt文本匹配的Regex函数
EN

Stack Overflow用户
提问于 2022-10-28 23:42:40
回答 3查看 82关注 0票数 0

我试图匹配图片alt文本中的两个值。在这些alt中也会有其他文本可以忽略。

财产要么是大小要么是作物。

alt标记看起来应该是:

大小: 16作物:中间crop"

  • alt="size: 16作物:关闭crop"

  • alt="size: 16作物:全body"

  • alt="size: 8作物:中间crop"

  • alt="size: 8作物:关闭crop"

  • alt="size: 8作物:完全body"

  • alt="size: 0作物:中间crop"

  • alt="size: 0作物:关闭crop"

  • alt="size: 0作物:完整身体“

对于大小,我试图得到"0“或"8”或"16“的作物,我试图得到”完整的身体“或”中作物“或”接近作物“

这个是可能的吗?

代码语言:javascript
运行
复制
function getImageProperty(image, property) {
  const regex = new RegExp(`${property}: (.+)[]]`, 'g');
  const matches = image.altText.match(regex);

  return matches && matches[1];
}

     /**
     * Returns a matching product image for provided size and crop.
     */
    const getMatchingImage = (images: size, crop) => {
      return images.find(
        (image) =>
          getImageProperty(image, size) && getImageProperty(image, crop),
      );
    };
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-10-29 00:44:06

您可以使用这个regex,它将匹配在属性名称之后的所有内容,直到字符串的末尾或下一个属性名称:

代码语言:javascript
运行
复制
\bsize: (.*?)(?=\s\w+:|$)

size将被替换为适当的属性名。

代码语言:javascript
运行
复制
images = document.querySelectorAll('img')

properties = ['size', 'crop']

function getImageProperty(image, property) {
  const regex = new RegExp(`\\b${property}: (.*?)(?=\\s\\w+:|$)`)
  const matches = image.getAttribute('alt').match(regex)
  return matches && matches[1]
}

[...images].forEach((img, i) =>
  properties.forEach(prop => console.log(`image ${i} ${prop} = ${getImageProperty(img,prop)}`))
)
代码语言:javascript
运行
复制
<img alt="size: 16 crop: mid crop" />
<img alt="crop: close crop size: 16" />
<img alt="size: 16 crop: full body" />
<img alt="crop: mid crop size: 8" />
<img alt="size: 8 crop: close crop" />
<img alt="size: 8 crop: full body" />
<img alt="size: 0 crop: mid crop" />
<img alt="size: 0 crop: close crop" />
<img alt="crop: full body size: 0" />

票数 2
EN

Stack Overflow用户

发布于 2022-10-29 01:05:49

"size: 16 crop: mid crop"格式是不起威慑作用的,因为在大小值之后没有分隔符,比如"size: 16, crop: mid crop"

您可以使用负面展望来解决以下问题:

代码语言:javascript
运行
复制
  const regex = new RegExp(`${property}: (\\w+( (?!crop:)\\w+)?)`);

如果您控制alt文本并选择,作为分隔符,则可以将regex更改为:

代码语言:javascript
运行
复制
  const regex = new RegExp(`${property}: ([^,"]+)`);

更新:

下面是一个工作示例,它似乎是您的image对象格式:

代码语言:javascript
运行
复制
function getImageProperty(image, property) {
  const regex = new RegExp(`${property}: ([^,"]+)`);
  const matches = image.altText.match(regex);
  return matches && matches[1];
}

[
  'size: 16, crop: mid crop',
  'size: 16, crop: close crop',
  'size: 16, crop: full body',
  'size: 8, crop: mid crop',
  'size: 8, crop: close crop',
  'size: 8, crop: full body',
  'size: 0, crop: mid crop',
  'size: 0, crop: close crop',
  'size: 0, crop: full body'
].forEach(str => {
  let image = { altText: str };
  console.log(image.altText
    + '\n=> size: ' + getImageProperty(image, 'size')
    + '\n=> crop: ' + getImageProperty(image, 'crop')
  );
});

票数 2
EN

Stack Overflow用户

发布于 2022-10-29 03:16:42

使用regex的替代方法是使用split()并从altText字符串中获取比较值。

altText.split(':')[1].split(' ')[1].trim()将返回大小

altText.split(':')[2].split(' ').join(' ').trim()将返回裁剪的值。

在代码片段中,我将图像对象、目标大小和裁剪的属性传递到getMatchingItem方法中。这将提取大小和裁剪值,并返回匹配的图像数组。在本例中,我匹配裁剪后的值和大小,以查找具有相同值的对象并在页面上显示它们。

如果这不是你要找的,请告诉我。

代码语言:javascript
运行
复制
function getMatchingImage(list, size, property) {
  // set the output to null or some string initially
  let output = [];
  // iterate over the image elements
  list.forEach((img, index) => {
    // get the alt attribubtes string
    const alt = img.altText
    // use split for each targeted value size and crop at the colon
    // then take the second indexed string and split again 
    // at the second spaces index and trim any white space JIC
    let altSize = alt.split(':')[1].split(' ')[1].trim()
    // repeat split and get the third indexed string and again split using spaces 
    // join the resulting remaining indexed strings and trim them
    let altCrop = alt.split(':')[2].split(' ').join(' ').trim()
    // conditional to check the image elements size and crop
    // matches the passed values size and property
    // if there is a match we push the value into an output array
    altSize === size && altCrop === property ? output.push(list[index]) : null
  })
  console.log(output)
  // return an array of values
  return output
}

// a method to display any matching images found
const displayFoundImage = (imgObjSrc) => {
  // iterate over list of found images
  imgObjSrc.map(imgObj => {
    // search through database images 
    return databaseImages.map(img => {
      // is there a match?
      if (img.src === imgObj.src) {
        // create an image element
        let imageEl = document.createElement('img')
        // set image elements src and alt attribute values
        imageEl.src = imgObj.src
        imageEl.alt = img.altText
        // append body and add image
        document.body.appendChild(imageEl)
        console.log(imageEl)
      }
    })
  })

}

const databaseImages = [{
    src: "https://picsum.photos/100/100",
    altText: "size: 16 crop: mid crop"
  },
  {
    src: "https://picsum.photos/101/100",
    altText: "size: 16 crop: close crop"
  },
  {
    src: "https://picsum.photos/102/100",
    altText: "size: 16 crop: full body"
  },
  {
    src: "https://picsum.photos/103/100",
    altText: "size: 8 crop: mid crop"
  },
  {
    src: "https://picsum.photos/104/100",
    altText: "size: 8 crop: close crop"
  },
  {
    src: "https://picsum.photos/105/100",
    altText: "size: 8 crop: full body"
  },
  {
    src: "https://picsum.photos/106/100",
    altText: "size: 8 crop: mid crop"
  },
  {
    src: "https://picsum.photos/107/100",
    altText: "size: 8 crop: close crop"
  },
  {
    src: "https://picsum.photos/108/100",
    altText: "size: 8 crop: full body"
  },
  {
    src: "https://picsum.photos/109/100",
    altText: "size: 0 crop: mid crop"
  },
  {
    src: "https://picsum.photos/110/100",
    altText: "size: 0 crop: close crop"
  },
  {
    src: "https://picsum.photos/111/100",
    altText: "size: 0 crop: full body"
  }
]

const foundImage = getMatchingImage(databaseImages, '8', 'full body')

displayFoundImage(foundImage)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74241845

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档