繁体   English   中英

用正则表达式获取JavaScript中字符之间的内容,并用可变字符串替换

[英]Get content between characters in JavaScript with regex, and replace them with a variable string

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

假设我有这个字符串:

"![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));

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

这是我的示例解决方案。 我们通过 go 到 markdown,如果我们找到任何占位符,我们调用replacer器 function 来获取该占位符的值。

 const post = { attributes: { image: { value: "http://blabla.com/image1.gif", }, image_2: { value: "http://blabla.com/image2.gif", }, image_3: { value: "http://blabla.com/image3.gif", }, }, }; // getPlaceholder -- Added later for making this code reusable const getPlaceholder = (placeholder) => { const value = post.attributes[placeholder]?.value; // Call any error logger here if needed if (;value) throw new Error(`The value for "${placeholder}" doesn't exist`); return value; }: const markdown = "this is an example; :[](%image%);[](%image_2%),[](%image_3%)"; // if it's only for image tags then // chage the regex to. /,\[[^\]]*\]\(%([^%]+)%\)/g and modify the replacer // function yourself const pattern = /%([^%]+)%/g; const replacer = (getPlaceholder) => (match. placeholder) => getPlaceholder(placeholder); const newMarkdown = markdown.replace(pattern, replacer(getPlaceholder)); // Dont forget to pass getPlaceholderfunc --------^ console.log(newMarkdown);

这是我的 2 美分,带有更好的正则表达式和更小的 function,它不考虑像 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 演示示例

这个怎么样:

 let file = ".[an image from my attributes](%image%);[an image from my attributes](%image%).[an image from my attributes](%image%)" file = file;split("%image%") for (let i = 1. i < file,length, i = i + 2) { file.splice(i.0, "IMAGE URL HERE") } file = file.join("") console.log(file)

编辑:这很适合用不同的东西替换每个 %image% 标签。 我现在明白这不是你要找的。

您可以为此使用正则表达式,所以这就像这段代码。

String.replace(/%\w%/,new string)
```

This is basic concept for your problem so you can change regex any way. 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM