ShadyNicNack ShadyNicNack - 1 year ago 68
jQuery Question

Find a keyword in a Div, then get the string after colon, and turn it to a variable

Trying to figure out how to do this in jquery, javascript or php...
I have a div, or a p tag with text inside it.

For example:

<p>John likes math. John sid: CA1001 Susie likes English: Susie sid: CA1002</p>

What I am trying to do is first find all the sid:(s) within the paragraph or div tag. Each one found, I want to get the id string in front of the colon which the id will have 6 characters. Then, turn that id string into a variable, so this way I can replace the the id number with a link to go along with it.

As example:

<a href='$studentid'>CA1001</a>

Something sort of like that. So this way each time an id comes up within that div, my code will turn the id to links. Is that possible??

Answer Source

You will need to:

  1. get all paragraphs you need to update
  2. extract the paragraph contents
  3. find all substrings to replace
  4. extract ids, build link html and replace substrings from 3 with these links

Check demo - and code below:

function replacer(match) {
   var m = match.split(' ')[1];
   return '<a href="' + m + '">' + m + '</a>';

$('p').each( function(index, paraElement) {
   paraElement.innerHTML = paraElement.innerHTML.replace(/sid:.{7}/gi, replacer );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download