0

I have the following words:

<a class="logo-home" href="#" title="abc xyz">abc xyz</a>
<img src="#" title="abc xyz" alt="abc xyz"/>
<h1>abc xyz</h1>
<p>blabla... abc xyz ... blabla</p>

I want to change string "abc xyz" to <span style="white-space:nowrap;">abc xyz</span> To do that, I use this code:

document.body.innerHTML = document.body.innerHTML.replace(/abc xyz/g, "<span style="white-space:nowrap;">abc xyz</span>");

But I don't want it change text in title attribute or atl attribute of element. All I want is just change text content in element. I try some regex but the problem still remain. Is Anyone have some advice for me? Many thanks.

2 Answers2

0

Looks like you are using Regex in JavaScript to replace html. Please don't use Regex to parse HTML. It is bad practice. Use DOMParser() instead.

But if your string is short and structure of HTML is similar like mentioned in question then try this:

var str = `<a class="logo-home" href="#" title="abc xyz">abc xyz</a><img src="#" title="abc xyz" alt="abc xyz"/>
<h1>abc xyz</h1>
<p>blabla... abc xyz ... blabla</p>`;

str = str.replace(/(?<=\<.*?\>.*)(abc\sxyz)(?=.*\<\/\w+\>)/g,'<span style="white-space:nowrap;">$1</span>');

console.log(str);
Ritesh Khandekar
  • 3,885
  • 3
  • 15
  • 30
0

If regex usage isn't actually mandatory here, I would suggest a different approach (a tree exploration for example)

Anyway, to answer your question using regexp (and especially, using the JS flavor of PCRE): you need to make sure that your "abc xyz" string is followed by a "<" before than a ">", right? Hence, try

abc xyz(?=[^<>]*<)

Explanations:

  1. abc xyz reads chars abc xyz
  2. (?=[^<>]*<) is a lookahead : it does not consumes any char but just make sure that the inner regexp is a success. So we should read chars that aren't < nor >, then a <

Example:

'<a class="logo-home" href="#" title="abc xyz">abc xyz</a>\
<img src="#" title="abc xyz" alt="abc xyz"/>\
<h1>abc xyz</h1>\
<p>blabla... abc xyz ... abc xyz ... blabla</p>'
.replace(/abc xyz(?=[^<>]*<)/g, 'hello world')

Result is : <a class="logo-home" href="#" title="abc xyz">hello world</a><img src="#" title="abc xyz" alt="abc xyz"/><h1>hello world</h1><p>blabla... hello world ... hello world ... blabla</p>

David Amar
  • 247
  • 1
  • 5