0

This is similar to other questions, but it's about something specific.

The first example doesn't do anything (breaks)

The second example works except that it hacks up html tags (specifically a tags) as well, so href="something with numbers" get hashed and then the whole thing falls apart

Then I get anchors that have their href attributes hashed up with span tags. Obviously that isn't what I want. What am I doing wrong? There must be some way to put all numbers and ", - : ()" inside a span without hashing up the html tags themselves.

$('#main-content p').contents().not("a").html(function(i, v) {
    return v.replace( /([0-9(),-:]+)/g , '<span class="number">$1</span>');
});


$('#main-content p').html(function(i, v) {
    return v.replace( /([0-9(),-:]+)/g , '<span class="number">$1</span>');
});
Oriol
  • 274,082
  • 63
  • 437
  • 513
Gambai
  • 651
  • 1
  • 7
  • 25
  • You were on the right path with .contents(), you then need to filter the contents to only text nodes (type = 3), and then loop over each one doing the replace on it's node value. – Kevin B Jul 08 '14 at 20:33

1 Answers1

1

You are replacing all number. You need to only select the text nodes within the element. This code is not tested, but should work.

EDIT: You have to also call .contents(). See this answer

EDIT 2: I got it working in this FIDDLE. Let me know what you think. Did you mean to replace special characters as well as numbers?....because that is what is currently happening per your original regEx.

$('p').contents().filter(function () { return this.nodeType === 3; }).each(function(){
    $(this).replaceWith($(this).text().replace( /([0-9(),-:]+)/g , 
    '<span class="number">$1</span>'));
 });
Community
  • 1
  • 1
joshboley
  • 1,143
  • 6
  • 10
  • `$('#main-content p').filter(function () { return this.nodeType === 3; })` will be empty, because `p` elements have `nodeType == 1` – Oriol Jul 08 '14 at 20:12
  • ok, indeed this.nodeType === 3 did not work nodeType == 1 leaves me with the same problem, hashed up anchor tags – Gambai Jul 08 '14 at 20:15
  • thank you, but I tried both again, still no good, with .contents() this time – Gambai Jul 08 '14 at 20:20
  • Can you create a fiddle so we can test it? – joshboley Jul 08 '14 at 20:20
  • sorry, I've never really used fiddle before, I tried to do something here http://jsfiddle.net/2t54V/ Sorry I'm not a better help – Gambai Jul 08 '14 at 20:36
  • ok, I got it working in jsfiddle. I mean I got jsfiddle working. the question is still not solved. thanks for everyone for helping – Gambai Jul 08 '14 at 20:49
  • Ok. It works now without destroying your a tag. I changed the href because it was throwing an error for google maps. – joshboley Jul 08 '14 at 21:08