Skip to content

Instantly share code, notes, and snippets.

@mchelen
Last active January 31, 2020 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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 30, 2020

I like #1 since the intent seems clear and straightforward.

#2 is hard to follow, even if effective.

I might like #3 better if I could store the regex in an intuitive/intent-revealing variable name.

@mchelen
Copy link
Author

mchelen commented Jan 31, 2020

Yeah, I think I agree for this use case.

#1

  • violates DRY by repeating the variable name
  • when looking at things like inputString.indexOf(':') + 1 it can be hard to tell what that + 1 is doing

#2

  • violates DRY with the delimiter
  • thinking through the split / slice / join steps is more complicated

#3

  • reading regex is usually not intuitive

@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