Fuhrmanator
Fuhrmanator

Reputation: 12922

Cut last n characters off of a String

Pharo beginner here - I've got some (ugly?) code that works for a specific case, but wonder if there's a better (more readable) way. I want to get the name of a repo without the .git at the end (if it's there).

Trimming off n characters would be great. I'm looking for a general solution.

I found trimRight: but it's not a number of characters; it's either white space or specific characters.

(projectName endsWith: '.git')
        ifTrue: [ projectName := projectName 
            copyFrom: 1 to: projectName size - '.git' size - 1 ]

Upvotes: 2

Views: 164

Answers (2)

Carlos E. Ferro
Carlos E. Ferro

Reputation: 948

For these cases where you want to remove a specific suffix if it is present, you have exactly #withoutSuffix:.

In your case, it should be

projectName withoutSuffix: '.git'

Upvotes: 7

Uko
Uko

Reputation: 13396

’Hello World’ allButLast: 2 => ‘Hello Wor’

Upvotes: 4

Related Questions