首页 > 解决方案 > 查找不在 url 字符串内的 2 个字符串之间的斜线

问题描述

我正在寻找一种方法/正则表达式来查找 2 个字符串之间的斜线并在其中添加一个   (空格)。我想从中排除 html 标签和 url。

我试图\/(?![^<>]*>)找到/替换斜线,它也排除了 html 标签。

string.replace(new RegExp('\/(?![^<>]*>)', 'gm'), '/&nbsp;');

我该怎么做才能从该正则表达式中排除网址?

正则表达式测试器: 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/&nbsp;test2
2.) <span>test1/&nbsp;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/&nbsp;test2 www.test1.com/test2 test3/&nbsp;test4
8.) <div>test1/&nbsp;test2 www.test1.com/test2 test3/&nbsp;test4</div>

提前致谢。

标签: javascriptregex

解决方案


输入字符串看起来像 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, "/&nbsp;");

console.log(output);

您可能想要更改urlRegExp我不确定它是否匹配所有有效 URL 或是否有误报。


推荐阅读