首页 > 解决方案 > 使用正则表达式获取 JavaScript 中字符之间的内容,并用变量字符串替换它们

问题描述

我正在研究如何用其他东西替换特殊字符(在本例中为百分比符号)之间的一些文本。这里有一些答案可以做到这一点,但我需要一些额外的东西,这让我更难找到如何去做。

假设我有这个字符串:

"![an image from my attributes](%image%)"

我想替换%image%为存储在image某处变量中的东西。问题是:我不知道事先存在哪些变量。

所以我需要解析'%%'之间的每个字符串,检查一个变量,如果存在,用别的东西替换它。

通过这样做,我设法得到了我想要的东西:

const insertAttributeLinks = (markdown, post) => {
  let alter = markdown;
  const regexp = /[^%%]+(?=%)/g;
  const matches = markdown.match(regexp) || [];
  matches.forEach((match, index) => {
    if (index % 2 !== 0) {
     // So it just gets the actual string I want to replace;
      alter = alter.replace(`%${match}%`, post.attributes[match]?.value);
    }
  });
  return alter;
  };
  
const markdown = 'this is an example: ![](%image%) ![](%image_2%) ![](%image_3%)';
const post = {
  attributes: {
    image: {
      value: 'https://static.wikia.nocookie.net/5ef5d627-c162-4309-ab47-e09f6b411883'
    },
    image_2: {
      value: 'https://media3.giphy.com/media/MBZuMSqKlqHC4lDIci/giphy.gif'
    },
    image_3: {
      value: 'https://www.icegif.com/wp-content/uploads/rickroll-icegif-5.gif'
    }
  }
}

console.log(insertAttributeLinks(markdown, post));

但我担心,现在的方式,我解析了 3 次 mardown,每次只更改一个变量,这可能会失控。我对那里的“如果”并不特别满意。你有什么建议?

标签: javascript

解决方案


这是我的 2 美分,它有一个更好的正则表达式和一个更小的函数,它不考虑像 ie: 这样的字符串,%test%因为这不应该是替换的正匹配:

/**
 * Replace Markdown's Image palceholder ![](%this%) with a property value.
 * @param {String} markdown Markdown String
 * @param {Object} attr Object with attribute: "value" replacements
 */
const MD_replaceImgValue = (markdown, attr) => markdown.replace(
  /(?<=!\[[^\]]*\]\()%([^%]+)%(?=\))/g, (m, p) => attr[p] || m
);



const markdown = `[Keep this as is](%unknown%) I like
this ![an image from my attributes](%image%) and 
also here's another ![Foo bar baz](%image_2%).
For example ![Lorem](%image_3%)`;

const post = {
  attributes: {
    image:   {value: 'https://example.com/img1.png'},
    image_2: {value: 'https://example.com/img2.png'},
    image_3: {value: 'https://example.com/img3.png'}
  }
};

// Modify slightly the post data to accommodate for our needs 
const attr = Object.entries(post.attributes)
  .reduce((a, [k,v]) => (a[k] = v.value, a), {});

// Test:
console.log(MD_replaceImgValue(markdown, attr));

这是Regex101.com 演示示例


推荐阅读