views:

55

answers:

1

Hi All,

I'm just starting out with JQuery.

My Question: I want to know if I can modify this code below to shorten long URLs, but ignore anything that isn't a URL?

My Problem: This code fragment targets everything in the DIV ('tasks-overflow'). Although I just need it to affect URL's in that DIV based on protocol(http://...). There are sentences on either side of the URL.

$(document).ready(function(){
  $(".tasks-overflow:contains('http://')").each(function(){
    $(this).text("http://...");
  });
});

Any help would greatly be appreciated, thanks

+2  A: 

Changed my awnser after I read your question better. Try this:

$(document).ready(function(){
  $(".tasks-overflow:contains('http://')").each(function(){
    var self = $(this)
    , txt = self.text();
    txt = txt.replace(/(http[s]*:[\/\\]{2})[^\s]*/g,'$1...');
    self.text(txt);
  });
});
BGerrissen
Hi BGerrissen,Firstly thank you for your effort. I have implemented the solution as you said...although it hasn't worked.I copied the first code fragment and created a new file called jquery-truncatedtext.js, and called it in via <script lang... . Then I copied the second code fragment into the file I'm attempting to apply the changes within.I then attemted to test it and nothing...am I doing something wrong?
Nasir
There seem to be some strange naming issues, but the code will do what you want. Inside the .each(function(){...}); All you need is the following:$(this).text($(this).text().replace(/(http[s]*:[\/\\]{2})[^\s]*/g,'$1...'));
Java Drinker
Hi Java Drinker,I've tried your code following your instruction...unfortunately the reg eppression is causing an error...even when I test it nothing changes
Nasir
Nasir, I made a typo in the code, fixed it, tested it and works:And if you want it to work with links, change the css expression to ".tasks-overflow a".
BGerrissen
@Java Drinker, each $(this) call creates a new jQuery object. Not really an issue, but better to avoid it by caching $(this) to a variable ;)
BGerrissen
BGerrissen...man you're a genius...it's working...thanks a trillion
Nasir