Sometimes, we want to remove first and last slash with a JavaScript regular expression.
In this article, we’ll look at how to remove first and last slash with a JavaScript regular expression.
How to remove first and last slash with a JavaScript regular expression?
To remove first and last slash with a JavaScript regular expression, we can use the /^\/|\/$/g
regex.
For instance, we write
const newString = theString.replace(/^\/|\/$/g, "");
to call theString.replace
with the /^\/|\/$/g
regex to replace all matches in the theString
string with empty strings.
^\/
matches the starting slash.
\/$
matches the ending slash.
|
combines the 2 patterns together with OR.
g
makes the regex match all instances of the patterns.
Conclusion
To remove first and last slash with a JavaScript regular expression, we can use the /^\/|\/$/g
regex.