Home > front end >  How do I find integers on either side of a hyphen and wrap the whole phrase in an element, using Jav
How do I find integers on either side of a hyphen and wrap the whole phrase in an element, using Jav

Time:03-09

Let's say I have these strings on an HTML page:

21 234-543 392 738 to 321

I want to use a regex expression to find only phrases that have a hyphen in them, so that the regex lets me select the string 234-543.

Once that string is selected, I want to wrap the whole phrase in a <span> element. So the resulting HTML would read: <span>234-543</span>.

Please see my snippet here using jQuery which demonstrates what I'm trying to do. This is what I have attempted so far, but it doesn't seem to be working.

  $(document).ready(function() {

        var div = $('.stats').html();

        var regex = new RegExp('/((?:\w -) \w )/g');

        if (regex.test(div)) {

            console.log('I found phrases with hyphens, yay!');

            // Wrap the matches in a <span> element somehow

        }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div >
  2-24<br>
  234<br>
  320-234<br>
  10<br>
  1028<br>
  201-234
</div>

Many thanks for considering my question.

CodePudding user response:

You may replace on the pattern \w (?:-\w ) :

var input = `<div >
  2-24<br>
  234<br>
  320-234<br>
  10<br>
  1028<br>
  201-234
</div>`;
var output = input.replace(/(\w (?:-\w ) )/g, "<span>$1</span>");
console.log(output);

CodePudding user response:

Hope this is what you're looking for:

var div = document.querySelector('.stats');
var newHtml = div.innerHTML.replaceAll(/[0-9] -[0-9] /g, '<span>$&</span>');
div.innerHTML = newHtml;
  • Related