0

Basically, i would like to add a class to a phone number thats inside a <p> tag with a heap of other text.

The CMS their using won't allow me to add HTML to the content, so i am left with jQuery.

I am trying to write a script that looks for the phone number inside very single <p> tag, and replaces only the number with no other changes to the surrounding text.

The script i have so far removes the entire <p> content, and leaves only the phone number, where as i just want to replace the phone number with a span tag and class.

I'm still new to jQuery, so i'm pretty much stuck here,

Here is my script so far:

$("p").each(function () {
   if ($(this).is(':contains("(02) 88506226")')) {
       console.log('yes');
       $(this).html('<span class="phone">(02) 88506226</span>');
   } else {
        console.log('no');
   }
});

Would appreciate any help anyone can offer :]

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Khadesa
  • 91
  • 3
  • 11
  • Start by collecting the current HTML with `.html()`. Then use a regular expression to search for the phone number and replace it. Then just set the html again with `.html(replacedString);`. You might want to read the answer to this question though: https://stackoverflow.com/questions/4338267/validate-phone-number-with-javascript Phone numbers are complex data and unless you know the exact format, it'll be pretty impossible to do a correct search and replace without using a library. – icecub Nov 14 '18 at 00:37
  • the code doesn't have a problem. it works like as you code. to know your intention, show the sample element structure (before/after) – Chase Choi Nov 14 '18 at 00:49
  • If the phone number is inside a span tag, search for the span tag instead of

    , then the full replace is fine.

    – lod Nov 14 '18 at 01:35

0 Answers0