Getting the first and last part of a string in JavaScript

Steven Script
Aug 24, 2017 · 1 min read

Here are some useful JavaScript string parsing snippets to get the first and/or last part of a string with a delimiting character.

//get the first part of the string before the colon (filter)
let str = “filter:Default”;
test = str.slice(0, str.indexOf(‘:’));
console.log(test); //outputs filter
//get the file extension of the filename string (json)
str = “bob.json”
let extension = str.substr(str.lastIndexOf(‘.’) + 1);
console.log(extension); //outputs json
//a shorter way to also get the extension from the filename string
extension = str.split(‘.’).pop();
console.log(extension); //outputs json
)
Steven Script

Written by

I’m a Web Developer riding up and down the learning curve and sharing things as I go.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade