Skip to content

Instantly share code, notes, and snippets.

@mchelen
Last active January 31, 2020 20:49
Show Gist options
  • Save mchelen/f673ba1dea5bbf5e3c7bea73a7d98487 to your computer and use it in GitHub Desktop.
Save mchelen/f673ba1dea5bbf5e3c7bea73a7d98487 to your computer and use it in GitHub Desktop.
Javascript ES6 String Prefix Removal 3 Ways
/*
How to remove a string prefix based on a delimiter, without knowing the length of the prefix.
#1 substr() + indexOf()
#2 string.split() + array.join()
#3 string.replace() + regex
*/
// example input
const inputString = "search_field:http://www.example.com/welcome:_visitor/index.html"
// const inputString = "search_url:http://www.example.com/welcome:_visitor/index.html"
// const inputString = "homepage:http://www.example.com/welcome:_visitor/index.html"
// #1
let value = inputString
.substr(
inputString.indexOf(':') + 1
);
console.log(value);
// #2
value = inputString
.split(':')
.slice(1)
.join(':');
console.log(value);
// #3
value = inputString
.replace(
/^[^:]+:/,
''
);
console.log(value);
@bengm
Copy link

bengm commented Jan 31, 2020

Regarding 3, I'm even thinking something like below could explain the regex via variable name.

everythingBeforeFirstColon = /^[^:]+:/;
value = inputString
  .replace(
    everythingBeforeFirstColon,
    ''
  );
console.log(value);

Adds a line, but could add some clarity vs. mentally parsing what the regex is supposed to do.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment