javascript - Node.js 正则表达式删除 url 中的撇号
问题描述
我需要替换字符串中的所有撇号,只有 href="" 标记中的撇号,外部的撇号应该保留。
我正在使用 node.js。
这是我的字符串:
This is an example text. I'd love to fix this.
<a href="https://www.example.com/i'd-love-to-fly/"> I'd love to fly link </a>
Inside the text there could be more urls
<a href="https://www.example.com/i'd-rather/">I'd rather link</a>.
例如
<a href="https://www.example.com/i'd-love-to-fly/"> I'd love to fly link </a>
应该
<a href="https://www.example.com/id-love-to-fly/"> I'd love to fly link </a>
我正在尝试使用正则表达式
/https[^"]++/
它选择了整个 URL,但我不知道如何只选择和替换撇号
解决方案
假设您在 URL 中只有一个单引号,则可以这样做:
(href="[^"]+)'([^"]+")
https://regex101.com/r/6zRLSC/1
如果您有多个单引号,则 while 循环可以解决该问题。
var string = `This is an example text. I'd love to fix this.
<a href="https://www.example.com/i'd-love-to-fly-but-don't-like-heights/"> I'd love to fly but don't like heights link </a>
Inside the text there could be more urls
<a href="https://www.example.com/i'd-rather/">I'd rather link</a>.`;
// While we match the pattern that we're targeting, keep on replacing
while(string.match(/(href="[^"]+)'([^"]+")/))
{
string = string.replace(/(href="[^"]+)'([^"]+")/g, '$1$2')
}
console.log(string);
推荐阅读
- mysql - MySQL GROUP BY 子查询中的功能依赖
- css-animations - 使用 css 动画淡出一个图像并淡入另一个图像
- ios - 在 Swift 中同时发送消息和关闭键盘
- algorithm - 如何解决这种重复以找出时间复杂度
- spring-kafka - @StreamListener 的自动启动
- javascript - p5.js 和 p5.sound.js 不适用于不同的机器
- r - R:如何在条形图中显示范围?
- jquery - Yajra DataTables:无法在表中加载记录
- javascript - Firebase 云函数 - null user.displayName onCreate
- angular - 如何在角度中找不到图像 src 404 时创建条件