How to Truncate / Trim Text By Sentence in JavaScript (not word or character)

Many times for showing a preview of longer text, I prefer not just to show a certain amount of characters (although it looks better visually) but to break it via sentence. Below is a small JavaScript function (I use it in NodeJs a bunch) that I’ve used to do this. No, it’s not the most complicated thing ever, but I wanted to share in case it helps anyone.

String.prototype.truncateBySent = function(sentCount = 3, moreText = "") {
  //match ".","!","?" - english ending sentence punctuation
  var sentences = this.match(/[^\.!\?]+[\.!\?]+/g);
  if (sentences) {
    console.log(sentences.length);
    if (sentences.length >= sentCount && sentences.length > sentCount) {
      //has enough sentences
      return sentences.slice(0, sentCount).join(" ") + moreText;
    }
  }
  //return full text if nothing else
  return this;
};

Easy to use, just do something like this:

someText.truncateBySent(2);

Sometimes you also want to include something at the end to indicate there is more text, like a link or ellipsis. You can do this:

someText.truncateBySent(2,' <a href="#">View More</a>');

It will take a line of text like this:

Sample sentence one? Another sentence two. Another three. Is there four? What about five? And six! Finally seven.

And return this:

Sample sentence one? Another sentence two. View More

See a working sample here: https://codepen.io/chrisbitting/pen/oNvzKNz

Or grab it on GitHub: https://github.com/cbitting/jsTruncateBySentence

How to Truncate / Trim Text By Sentence in JavaScript (not word or character)

Angular Pipe (or just Javascript) to Convert 24 Time to 12 Hour Format

I’m storing time in my database as 24 hour format (ie: “13:00” [1:00 PM]) because it’s easy and has a bunch of advantages. But on the front-end, in Angular, I want to show these as a 12 hour format. One way to do this is with a Pipe that will allow you to transform the time to 12 hour. Before creating the below I looking for something existing, but didn’t find anything that seemed to fit and work well, so below is what I use.

This is the function in the pipe (can be used in Javascript for those w/o Angular): (try in jsfiddle)

var time24To12 = function(a) {
    //below date doesn't matter.
    return (new Date("1955-11-05T" + a + "Z")).toLocaleTimeString("bestfit", {
        timeZone: "UTC",
        hour12: !0,
        hour: "numeric",
        minute: "numeric"
    });
};

When called and passed a time, like:

time24To12('13:00')

It will return the 12 hour version:

1:00 PM

Okay, so how to add a new Pipe and use it in Angular?

  1. Create a new file “time24to12.pipe.ts
  2. File contents should be the below:
import { Pipe, PipeTransform } from '@angular/core';


@Pipe({ name: 'time24to12Transform' })
export class Time24to12Format implements PipeTransform {
  transform(time: any): any {
    
 var time24To12 = function(a) {
    //below date doesn't matter.
    return (new Date("1955-11-05T" + a + "Z")).toLocaleTimeString("bestfit", {
        timeZone: "UTC",
        hour12: !0,
        hour: "numeric",
        minute: "numeric"
    });
};

    return time24To12(time); 
  }
}

3. Make sure in your app.module.ts you import this file:

import { Time24to12Format } from './time24to12.pipe';

…and also add it to the declarations section:

@NgModule({
  declarations: [
   ...
    Time24to12Format,
 ...

4. Now you can use it in views, like below:

{{yourobject.time | convertFrom24To12Format}}

Hope this helps someone. No, this code doesn’t check beforehand for correct time input formatting or perform many other things it should, it just trusts you.

Angular Pipe (or just Javascript) to Convert 24 Time to 12 Hour Format

Google Chrome – Getting Entire List of Twitter Followers

The Bad:

Warning: this is an unofficial, non-Twitter approved way to easily gett a list of your Twitter followers.

The Good:

This is a really easy, can’t hurt anything method. Using just Google Chrome Developer Tools (part of the browser). But hey, if Twitter sends you a nasty letter, please don’t blame me.

The Scenario:

As of today, Twitter only shows about 18 of your followers at once. As you scroll down on your page, it loads another 18, so on and so on. If you have thousands of followers, getting to your first followers is kind of a pain, and would take forever. The below few chunks of javascript basically scroll the page to the end, and allow you to see the entire list.

Step 1. Open dev tools by hitting F12.

Step 2. Click the Console tab (maybe between Elements and Sources).

Step 3. Visit your followers page (ie: twitter.com/username/followers).

Step 4. Paste the below code into the Console (next to the “>”):

for (i = 0; i < 5000; i++) {

    setTimeout(function() {

        if ($(".has-more-items")[0]) {
        
            window.scrollTo(0, document.body.scrollHeight);

        } else {
           
           //console.dir('Finished.');
        }

    }, i * 1000);

}

Step 5. When it finished at and the bottom of your page, run the below to get a list of your followers copied to the clipboard:

var r = '';
$( ".ProfileCard-screenname .u-linkComplex-target" ).each(function( index ) {
r = r + $(this).text() +  "\n";
});

console.dir(r);
copy(r);

 

Bonus:
Do the above Step 4 on your “following” page, and then run the below to show people you’re following, but don’t follow you:

$( ".u-size1of2:has(.FollowStatus)" ).hide();
Google Chrome – Getting Entire List of Twitter Followers

Creating a Chrome Plugin to Scrape A Page (using jQuery)

If you’ve played w/ Chrome extensions at all, you know they are super powerful. I recently wanted to visit a bunch of pages, and extract some info from each page. I could easily run some jQuery script in the console of each page to do this, but I wanted a quick and easy way to do this. Creating a Chrome extension, that includes jQuery, to run locally is pretty simple. Below are the different files (5 of them) you’ll need (put these all in a single folder).

After creating these and adding your code, add to Chrome by going to Extensions > Load unpacked extension and choose your folder.

1: manifest.json

{
 "name": "Your Extension Name",
 "description": "This was easy",
 "version": "1.1",
 "background": {
 "scripts": [ "jquery-3.1.1.min.js","background.js","content.js"]
 },
 "permissions": [
 "tabs", "http://*/*", "https://*/*"
 ],
 "browser_action": {
 "default_title": "My Extension Title",
 "default_icon": "a-cool-logo.png"
 },
 "manifest_version": 1
}

2: jquery-3.1.1.min.js (get a copy from jquery.com)

 

3: a-cool-logo.png (16px x 16px)

 

4: background.js

chrome.browserAction.onClicked.addListener(function(tab) {
 chrome.extension.getBackgroundPage().console.log('your plugin gonna do something');
//maybe see if your plugin should be allowed to run
 if (tab.url.indexOf("/maybeCheckAurl/") !== -1) {
 
chrome.tabs.executeScript(null, { file: "jquery-3.1.1.min.js" }, function() {
 chrome.tabs.executeScript(null, { file: "content.js" });
});
 
 }
 
});

5: content.js (the magic happen here)

//i check to make sure jQuery is loaded
if (jQuery) { 
 
 jQuery(".someclass a").each( function() { 
 
//log the results 
 console.log($(this).attr("href"));

//maybe do something with them
 $.get( "http://yourapi"), function( data ) {});
 
 });
 
} else {
 alert('no jq');
}
Creating a Chrome Plugin to Scrape A Page (using jQuery)

Upgrading / Updating your Node.js & NPM to Latest Version on Windows

If you’re running Node on Windows (who isn’t? [don’t answer that]), updating Node.js & NPM to the latest version is a little different than on Linux or OSX. In some ways, it’s easier than you might think.

To update these, the easiest way I have found is to download the latest version of Node.js (NPM is included) from the Node site here. Choose 32bit or 64bit (depending on your setup) and install.

Now if you run “node -v” or “npm -v” you’ll see you have the latest and greatest.

node-update

Upgrading / Updating your Node.js & NPM to Latest Version on Windows