Remove trailing hyphen in a string in a Jenkinsfile

Viewed 323

In my project, branches sometimes have a hyphen in them. This is due to Jira's peculiar naming process. A branch might automatically be named PROJ-3421-create-a-login- This happens because Jira is chopping off the rest of the sentence and leaving a hyphen at the end.

This trailing hyphen messes up Jenkins. I'm trying to figure out how to strip it.

I'm trying something like this. It's not valid code. After this step the value is used in the script.

How do we strip a trailing hyphen in a Jenkinsfile?

pipeline {
  environment {
    imageName = "example.org/myapp/myapp-${env.BRANCH_NAME.toLowerCase()}"
  }
  agent any
  stages {
    stage('Fixup Variables') {
      steps {
        script {
          imageName = StringUtils.stripEnd(imageName, "-")
        }
      }
    }
  }
}
1 Answers

The easiest way to do this would be with a regular expression string replacement. The regular expression would match any - character at the end of the string. I would also recommend modifying the string within the environment directive to be cleaner and guarantee scope within your pipeline:

environment {
  imageName = "example.org/myapp/myapp-${env.BRANCH_NAME.toLowerCase().replace('-$', '')}"
}
Related