jQuery, remove certain chunks of text

Is it possible, using jQuery (Or anything else), to remove certain bits of text from an element but leave the rest intact?

I’m using a WordPress plugin that compiles all my tweets into WP posts but the post titles are automatically saved using the full text body of the tweet. For example;

Read More

@username http://t.co/XXXXXXXX #hashtag

I want to be able to remove the hyperlink and also the #hashtag

The hashtag will always be the same (Ie; it will always be #hashtag), but the hyperlink will change with every post. Is there a way that I can do this?

Related posts

Leave a Reply

3 comments

  1. Things could be harder or easier depending on whether the username, link and hashtag are always in the same position of the tweet or not. But I might suggest splitting the tweet string on ‘ ‘ and looping to construct a string without words that begin with ‘@’, ‘http://t.co‘, and ‘#’.

    It would be easier with a full example because you may not want to remove all the handles, usernames, and hashtags. But I do suspect there is some uniformity in the format you may want to exploit.

    Example:

       var words = $(el).text().split(' ');
       var cleaned = [];
       for (var i = 0, len = words.length; i < len; i++) {
             if (!(words[i].indexOf('@') === 1)) { // ... etc for other characters
                 cleaned.push(words[i]);
             }
       }
       var cleaned_string = cleaned.join(' ');
    
  2. You can use regular expressions to remove the url and the hastags, for example:
    To remove the http part:

    fullTweet.replace(/http://.+?s/g, "");
    

    The regular expression means http:// followed by any number of characters until a space (use non-eager, i.e. +?, meaning it will stop at the first space)

    To remove the hashtag

    fullTweet.replace(/#.+?(s|$)/g, "");
    

    Here it’s a # followed by any character until a space or end of string

    Here’s a complete example.

    Good reference for javascript regular expressions.

  3. Jquery Link:

    var test = "@username http://t.co/XXXXXXXX #hashtag";
    var matchindex = test.indexOf("#");
    alert(matchindex);   // Tells you at what index the hashtag starts
    var res = test.split("#");
    alert(res[0]); // Gives you rest of the string without hastag
    

    You can do something like this, to get the string without hashtag.You’ll have to get the whole text as string into a variable first.