Skip to content

Instantly share code, notes, and snippets.

@joseluisq
Last active June 14, 2023 09:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joseluisq/0989d5a323feec54e039ad851daa5c41 to your computer and use it in GitHub Desktop.
Save joseluisq/0989d5a323feec54e039ad851daa5c41 to your computer and use it in GitHub Desktop.
Javascript: Get part of string matching a Regular Expression and then pass its value to a callback

Pick part of an string using a Regex

Get part of string matching a Regular Expression and then pass its value to a callback

const pickStringByRegex = (pattern, str, func) => {
    const regex = new RegExp(pattern)
    const value = regex.test(str) ? str.replace(regex, '$2') : null

  if (value) {
    func(value)
  }
}

// Usage:

const pattern = /^(prefix_(V1|V2|V3|V4|V5))$/
const search = 'prefix_V2'

pickStringByRegex(pattern, search, (v) => console.log('Value matched: %s', v))

// > Value matched: V2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment