javascript - 查找不在 url 字符串内的 2 个字符串之间的斜线
问题描述
我正在寻找一种方法/正则表达式来查找 2 个字符串之间的斜线并在其中添加一个 (空格)。我想从中排除 html 标签和 url。
我试图\/(?![^<>]*>)
找到/替换斜线,它也排除了 html 标签。
string.replace(new RegExp('\/(?![^<>]*>)', 'gm'), '/ ');
我该怎么做才能从该正则表达式中排除网址?
正则表达式测试器: https ://regex101.com/r/40DzZP/1
例子:
在
1.) test1/test2
2.) <span>test1/test2</span>
3.) www.test1.com/test2
4.) www.test1.com/test2/test3
5.) <a>www.test1.com/test2</a>
6.) <a>www.test1.com/test2/test3</a>
7.) test1/test2 www.test1.com/test2 test3/test4
8.) <div>test1/test2 www.test1.com/test2 test3/test4</div>
出去
1.) test1/ test2
2.) <span>test1/ test2</span>
3.) www.test1.com/test2
4.) www.test1.com/test2/test3
5.) <a>www.test1.com/test2</a>
6.) <a>www.test1.com/test2/test3</a>
7.) test1/ test2 www.test1.com/test2 test3/ test4
8.) <div>test1/ test2 www.test1.com/test2 test3/ test4</div>
提前致谢。
解决方案
输入字符串看起来像 HTML,您可以将其解析为 HTML,遍历所有节点,将节点的文本拆分为不同的组件,如果它们不是 URL,则处理所有这些组件,这是一个示例:
const input = `test1/test2
<span>test1/test2</span>
www.test1.com/test2
www.test1.com/test2/test3
<a>www.test1.com/test2</a>
<a>www.test1.com/test2/test3</a>
test1/test2 www.test1.com/test2 test3/test4
<div>test1/test2 www.test1.com/test2 test3/test4</div>`;
const urlRegExp = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/i
const doc = new DOMParser().parseFromString(input, "text/html");
[...doc.body.childNodes].forEach((c) => {
const splitted = c.textContent.split(" ");
const processed = splitted.map(part => {
if (!urlRegExp.test(part.trim())) {
return part.replace(/\//g, "xxxx")
}
return part;
});
c.textContent = processed.join(" ");
});
const output = doc.body.innerHTML.replace(/xxxx/g, "/ ");
console.log(output);
您可能想要更改urlRegExp
我不确定它是否匹配所有有效 URL 或是否有误报。
推荐阅读
- dart - 是否可以使用 .where() 来“断言”一个类型?
- node.js - 如何以json字符串作为值解析json
- python - 使用 Python 进行 FFT
- visual-studio - 如何在 Visual Studio 中选择下一个重复选择?
- minizinc - Minizinc 目标函数用于计划中的差距
- cadence-workflow - 工作流事件的重新排序
- birt - 无法使用 javascript 设置 Birt 图表的 SeriesIdentifier
- node.js - 不生成招摇文档 - Node JS + swaggerJSDoc
- javascript - Firestore orderBy Timestamp DESC
- reactjs - 带分页的材料 Ui 表排序