Заменить подстроку javascript - PullRequest
0 голосов
/ 02 апреля 2020

Мне нужно заменить только подстроку из строки, совпадающую с моим регулярным выражением.

const text = "There are many variations of passages of Lorem Ipsum available,

<a href='https://stackoverflow.com/'>stackoverflow</a>

but the majority have suffered alteration in some form, by injected humor, or randomized words which 

<a href="/page2">page 2</a>

don't look even slightly believable.
If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text.
All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the";

Мне нужно добавить целевой пробел, чтобы все внешние гиперссылки были похожи на

const text = "There are many variations of passages of Lorem Ipsum available,

<a target='_blank' href='https://stackoverflow.com/'>stackoverflow</a>

but the majority have suffered alteration in some form, by injected humor, or randomized words which 

<a href="/page2">page 2</a>

don't look even slightly believable.
If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of the text.
All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the";

Ответы [ 2 ]

1 голос
/ 02 апреля 2020

Вместо того, чтобы делать это с регулярным выражением, вы можете добавить это HTML к элементу и затем установить атрибут для всех ссылок:

const text = '...';
const div = document.createElement('div');
div.innerHTML = text;
[...div.querySelectorAll('a[href]')].forEach(a => a.setAttribute('target', '_blank'));
const result = div.innerHTML;

И у вас есть _blank -ed HTML в вашем result конст.

0 голосов
/ 02 апреля 2020

Здесь много проблем

  1. JavaScript строки не могут иметь новых строк, литералы шаблона могут (см. Далее)
  2. Javascript строки, которые нужны в кавычках одного вида такие же кавычки, например "this is not "possible"", но "this is \"possible\""
  3. . Вы НЕ хотите использовать регулярные выражения для HTML

. Здесь я беру все ссылки, начинающиеся с http и установите цель

Я предполагаю, что у вас нет таких ссылок, как a href="http_is_a_protocol.html" Если у вас есть такая возможность, вам нужно использовать более умный селектор или посмотреть мою вторую версию

// Here I use a template literal backtick to contain newlines and quotes
const text = `There are many variations of passages of Lorem Ipsum available,

<a href='https://stackoverflow.com/'>stackoverflow</a>

but the majority have suffered alteration in some form, by injected humor, or randomized words which 

<a href="/page2">page 2</a>

don't look even slightly believable.
If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text.
All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the`;

const div = document.createElement("div")
div.innerHTML = text;
[...div.querySelectorAll("a[href^=http")].forEach(function(link) {
  link.target="_blank"; // or link.setAttribute("target","_blank")
  document.body.appendChild(div);
})

Более скучный на случай, если вам нужно проверить каждую ссылку - он будет вызывать все, что не на том же сервере, внешний

// Here I use a template literal backtick to contain newlines and quotes
const text = `There are many variations of passages of Lorem Ipsum available,

<a href='https://stackoverflow.com/'>stackoverflow</a>

but the majority have suffered alteration in some form, by injected humor, or randomized words which 

<a href="/page2">page 2</a>

don't look even slightly believable.
If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text.
All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the`;

const div = document.createElement("div")
div.innerHTML = text;
[...div.querySelectorAll("a[href]")].forEach(function(link) {
  const url = new URL(link.href);
  if (url.hostname != location.hostname) link.target="_blank";
  document.body.appendChild(div);
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...