remove slashes from beginning and end of string in typescript

To remove slashes from the beginning and end of a string in Typescript, you can use a combination of the replace() and trim() functions along with regular expressions. Here's an example code snippet:

index.ts
let myString = '/example/string/';

// Remove slashes from beginning and end of string
myString = myString.replace(/^\/|\/$/g, '').trim();

console.log(myString); // Output: "example/string"
191 chars
7 lines

In this code, we first define a string with slashes at the beginning and end. Then, we use the replace() method along with a regular expression to match the slashes at the beginning (^\/) and end (\/$) of the string. The g flag ensures that all matches are replaced.

Finally, we use the trim() method to remove any whitespace that might be left after the slashes are removed. The resulting string will be "example/string", without any slashes at the beginning or end.

gistlibby LogSnag