skip to Main Content

I want to concatenate three replace Regex code into one.
In the following example I have remove DIV, I, IMG tags from title. It’s a expected behavior. The only problem with concatenation.

Anyone help me achieve this.

text = $('.text').attr('title')
//console.log(text)
bind = text.replace(/<(span|i)[^>]*>.*?</1>/g, '').replace(/<img[^>]*>/g, '').replace(/</?div[^>]*>/g, '')
console.log(bind)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div title="Lorem Ipsum<div><img src='test.png'><i class='fa fa-check'></i></div>" class="text">Lorem Ipsum has been the industry's standard</div>

2

Answers


  1. Parsing HTML with RegExp is probably a bad idea and will result in a brittle solution.

    Why not just parse with DOMParser instead and then ask the resulting document for its innerText?

    const attribString = "Lorem Ipsum<div><img src='test.png'><i class='fa fa-check'></i></div>";
    const dp = new DOMParser();
    const doc = dp.parseFromString(attribString, "text/html");
    const text = doc.documentElement.innerText;
    console.log(text);
    Login or Signup to reply.
  2. I think DOMParser is a bit overkill. How about a solution using a temporary virtual div element? Snippet using vanilla js:

    const elem = Object.assign(
      document.createElement(`div`), {
        innerHTML: document.querySelector(`div.text`).title
      }
    );
    console.log(elem.textContent);
    <div 
      title="Lorem Ipsum<div><img src='test.png'><i class='fa fa-check'></i></div>" 
      class="text">
      Lorem Ipsum has been the industry's standard
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search