gpt4 book ai didi

javascript - JS/JQUERY : How to match and replace occurances inside specified strings?

转载 作者:行者123 更新时间:2023-12-01 03:40:07 24 4
gpt4 key购买 nike

我发誓我一整天都在尝试自己解决这个问题,但我的 regex-foo 并不是那么好。

我正在尝试创建一个小型解析器函数,将带有 url 的字符串转换为 html 编码和标签

我知道正则表达式试图找出从大字符串中转换哪些网址是多么复杂,所以我所做的只是在要转换的字符串前面添加一个标志来告诉解析器如何格式化它,并且发布后用“;”修复它char 告诉解析器该特定 URL 的结束位置。这样,解析器需要执行的 guest 工作就会减少,从而更容易进行正则表达式匹配并加快执行速度。我真的不需要概括匹配并替换全部。

所以我的格式如下,其中“X”是网址字符串:

  1. 对于 URL,将为 url=X;
  2. 对于图像,它将是 img=X;

所以我的前缀和后缀之间的任何内容都必须相应地转换..

例如,对于我文档中的图像,字符串可能是:

click this image img=http://example.com/image1.jpg;

我需要将其转换为

click this image <a href="http://example.com/image1.jpg" target="_blank">
<img class="img img-responsive" src="http://example.com/image1.jpg"/></a>

我可以在 PHP 购买 preg_match() 函数中轻松做到这一点

preg_match('/\img=(.+?)\;/i', $item_des, $matches)

这是代码块: enter image description here

我决定将此例程推送到浏览器而不是后端(PHP),因此我需要类似或更好的 JS 解决方案。

希望大家能帮忙,谢谢!

最佳答案

尝试下面的代码:

var str = "click this image img=http://example.com/image1.jpg;image2 img=http://example.com/image2.jpg;"
var phrases = str.split(';');
var totalRes = '';
phrases.forEach(function(str){
totalRes += processPhrase(str);
});
console.log(totalRes);
function processPhrase(str) {
var img = str.split('img=')
var res = '';
if (img.length > 1) { //img=X
var url = img[1].replace(';', '');
res = img[0] + "<a href='" + url + "' target='_blank'><img src='" + url + "'/></a>";
} else {
var url = str.split('url=');
//Do for url=X here
}
console.info(res);
return res;
}

关于javascript - JS/JQUERY : How to match and replace occurances inside specified strings?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43962469/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com