zsid zsid - 2 years ago 198
Javascript Question

Javascript regex: lookahead and lookbehind

I am trying to create a regex in javascript. What I want to do:


  1. I want to see if there is an html element with
    class=“get-me”
    anywhere in the string.

  2. If there is I want to replace it with
    I found you
    .



Examples:


  1. <div class="get-me" />



Result:
I found you



  1. <div>Some text <div class="get-me" data-type="data-type" js="js" /> more things happening here</div>



Result:
<div>Some text I found you more things happening here</div>



  1. <div>Some text <p class="get-me" /> more things</div>



Result:
<div>Some text I found you more things</div>



  1. I m testing <<<<div class="get-me" />



Result:
I m testing <<<I found you


Thanks.

Answer Source

Without getting into the parsing HTML debate, this will answer your original (unedited) question:

const replacementText = 'I found you';
const regex = /(.*)<\w+\s.*class="get-me".*\/>(.*)/;
let str = '<div>Some text <div class="get-me" data-type="data-type" js="js" /> more things happening here</div>';
str = str.replace(regex, `$1${replacementText}$2`);

Output is

"<div>Some text I found you more things happening here</div>"

Here is a JSBin for you: https://jsbin.com/rowaxayodu/edit?js,console

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download