javascript - 使用正则表达式获取 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,每次只更改一个变量,这可能会失控。我对那里的“如果”并不特别满意。你有什么建议?
解决方案
这是我的 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));
推荐阅读
- c# - 我在哪里可以在我的 Asp.Net Core 项目中保留经常更改的联系信息,以便我可以更新它(如配置文件)
- pytest - 是否可以指向 tox 从分支中提取依赖项(又名在幕后使用`pip -e`)?
- python-3.x - 如何在 Jinja 中对齐 Pandas DataFrame 列号文本
- haskell - 有没有一种高效、懒惰的方式将 foldMap 与 traverse 融合?
- python - 从python中的文本数据中提取数字和相邻单词
- java - 如何在springboot中自动装配jdbcTemplate?
- javascript - 更改图表的标签
- codenameone - 代号:Android 上的 DateTime-Pickcer 看起来丑陋/腐败
- tensorflow - 如何使用自微分特征计算向量相对于向量的导数
- r - 将两个向量组合成有序对列表