2020-09-16
|~2 min read
|321 words
Strings have a built-in replace
method that’s quite handy.
console.log("my longer string".replace("longer", "")) // 'my string'
Not only can you pass a string to search for (as I did above), but you can also pass regular expressions or variables:
/**
* @params filePath {string} the full filepath
* @params directory {string} the directory path to the file
* @example file('path/to/file/fileName.txt','path/to/file') // "fileName.txt"
*/
function file(filePath, directory) {
const pattern = `${directory}/`
return filePath.replace(pattern, "")
}
But, what if we wanted to also trim off the .md
and only if it was at the end of the string?
To indicate the end of the string, we’ll use the $
marker. But if we try to do the same thing we did with the directory, it won’t work:
/**
* @params filePath {string} the full filepath
* @params directory {string} the directory path to the file
* @params ext {string} the extension to strip
* @example file('path/to/file/fileName.txt','path/to/file') // "fileName" -- this won't work
*/
function file(filePath, directory, ext) {
const pattern = `${directory}/`
const ext = `.${ext}$`
return filePath.replace(pattern, "").replace(ext, "")
}
The problem is that the template literal isn’t actually treated as a regular expression.
In order to solve that problem, we can use the constructor to create a regular expression:
/**
* @params filePath {string} the full filepath
* @params directory {string} the directory path to the file
* @params ext {string} the extension to strip
* @example file('path/to/file/fileName.txt','path/to/file') // "fileName"
*/
function file(filePath, directory, ext) {
const pattern = `${directory}/`
const ext = new RegExp(`.${ext}$`)
return filePath.replace(pattern, "").replace(ext, "")
}
And just like that we’re able to use template literals within regular expressions. This is a contrived example, but from this we can see how we can merge template literals with the power of regular expressions. Of course, the bigger takeaway is that I need to learn more about the RegExp
constructor.
Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!