Last active
March 11, 2020 16:53
-
-
Save ruucm/e855a916e2ffb497e85bcb0ecfc6fc2a to your computer and use it in GitHub Desktop.
This file contains 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
function stringKnife(str, range, remove = false) { | |
if (typeof range == "number") range = [range, undefined]; | |
const [start, end] = range; | |
const sliced = str.slice(start, end); | |
if ((!remove && !end && start > 0) || (remove && start < 0)) | |
return str.replace(sliced, ""); | |
return sliced; | |
} | |
// Usage | |
// let myString = "Hello World3" | |
// 1. get string from the start : stringKnife(myString, 2) 👉 He | |
// 2. get string from the back : stringKnife(myString, -3) 👉 ld3 | |
// 3. get string from using range : stringKnife(myString, [6, 11]) 👉 World | |
// 4. remove string from the start : stringKnife(myString, 2, true) 👉 llo World3 | |
// 5. remove string from the back : stringKnife(myString, -2, true) 👉 Hello Worl | |
// A simplified version | |
// function stringKnife(str, range, remove = false) { | |
// let sliced = str.slice(range); | |
// if ((!remove && range > 0) || (remove && range < 0)) | |
// return str.replace(sliced, ""); | |
// return sliced; | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment