Yusaf Khaliq
Yusaf Khaliq

Reputation: 3393

Get string, extract id, and wrap text

If I have the HTML below:

<p> some random text :) video?v=E_LkHrerwe4lnhhnrCbo another video?v=567ghf564_-56e</p>
<p> some2 random2 text2 video?v=rt5y5yvbn5y</p>

Using jQuery how can I get the ID which is 8 characters after video?v= so for the first one the id will be E_LkHrer, then wrap the string with a <span id="'+8charID+'"></span>? Thus, for the HTML above it will return

<p> some random text :) <span id="E_LkHrer">video?v=E_LkHrerwe4lnhhnrCbo</span> another <span id="567ghf56">video?v=567ghf564_-56e</span></p>​
<p> some2 random2 text2 <span id="rt5y5yvb">video?v=rt5y5yvbn5y</span> </p>​

ATM I have this, but I don't know where to go from there and I know the jQuery doesn't have much to do with what I need I was just testing if I could try stripping an id from one video?v=

$("p").each(function() {
  var content = $(this).html();
  var getwatch = content.split('video?v=');
  $(this).after(getwatch[1].substring(0, 8));
});​
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p> some random text :) video?v=E_LkHrerwe4lnhhnrCbo another video?v=567ghf564_-56e</p>
<p> some2 random2 text2 video?v=rt5y5yvbn5y</p>

Upvotes: 1

Views: 416

Answers (1)

Yoshi
Yoshi

Reputation: 54649

$('p').html(function (_, str) {
  return str.replace(/video\?v=([^\s<]+)/g, function ($0, $1) {
    return ['<span id="', $1.substr(0, 8), '">', $0, '</span>'].join('');
  });
});​

http://jsfiddle.net/HcAyd/1/

Upvotes: 2

Related Questions