Last active
January 31, 2020 20:49
-
-
Save mchelen/f673ba1dea5bbf5e3c7bea73a7d98487 to your computer and use it in GitHub Desktop.
Javascript ES6 String Prefix Removal 3 Ways
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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); | |
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
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
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.