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); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Regarding 3, I'm even thinking something like below could explain the regex via variable name.
Adds a line, but could add some clarity vs. mentally parsing what the regex is supposed to do.