Getting the first and last part of a string in JavaScript
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
