Skip to content

Instantly share code, notes, and snippets.

@mchelen
Last active January 31, 2020 20:49
Show Gist options
  • Select an option

  • Save mchelen/f673ba1dea5bbf5e3c7bea73a7d98487 to your computer and use it in GitHub Desktop.

Select an option

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);
@mchelen

mchelen commented Jan 31, 2020

Copy link
Copy Markdown
Author

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

bengm commented Jan 31, 2020

Copy link
Copy Markdown

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