JMurky
JMurky

Reputation: 198

Add space after slashes that are not part of html tags

I want to add a space after each slash (/) character that is not part of an html tag. So if the content of an element looks like:

<strong>Occupational/technical/eduction/training program:</strong><br />
Started before 1/1/12.<br />
More text <i>description</i> more/text/with/slashes.

I'd like to add a space after each slash, but not slashes in closing tags (like the </strong>) or in break <br /> tags, as adding spaces after slashes in tags cause browsers to incorrectly render them.

Right now, I have:

jQuery("table tr td:nth-child(2)").each(function() {
    var tdContent = jQuery(this).html();
    slashSpace = tdContent.replace(/\//g, "/ ");
    $(this).empty().append(slashSpace);

});

Close, but this adds space to all slashes, including html tags. I set up this jsFiddle: http://jsfiddle.net/Ejp4r/. As you can see, adding space to closing tags renders the second cell incorrectly.

Seems like it should be fairly easy, but I'm drawing a blank. Any ideas?

Upvotes: 0

Views: 1996

Answers (4)

user229044
user229044

Reputation: 239230

Your regular expression needs to explicitly match only slashes that aren't surrounded by < or >:

tdContent.replace(/([^<])\/([^>])/g, "$1/ $2");

In a regular expression, [^...] means "match characters not in this set". The regular expression will now match */*, but not </ or />.

Works.

Upvotes: 4

Marcelo Pascual
Marcelo Pascual

Reputation: 820

If you don't want to get mess with regex, try this:

$("table tr td:nth-child(2)").each(function() {

    var children = $(this).find();

    if( children.length > 0 ) {
        children.each(function(){
            $(this).html( $(this).html().replace(/\//g, "/ ") ); 
        });
    } else {
        $(this).html( $(this).html().replace(/\//g, "/ ") );
    }

});

Upvotes: 0

Yoshi
Yoshi

Reputation: 54649

Alternative to using regular expressions, you could traverse the text-nodes to apply what needs to be changed:

var textNodes = function textNodes(parent, cb) {
  [].slice.call(parent.childNodes).forEach(function (node) {
    switch (node.nodeType) {
      case 1: textNodes(node, cb); break;
      case 3: cb(node); break;
    }
  });
};

$('table').each(function () {
  textNodes(this, function (node) {
    node.nodeValue = node.nodeValue.replace(/\//g, '\/ ');
  });
});

http://jsbin.com/ohezud/2/

Upvotes: 2

JAM
JAM

Reputation: 6205

Try using .text(...) instead of .html(...) like this FIDDLE

Upvotes: 0

Related Questions