1

I wish to know how to test strings composed of certain string and characters. I've tested

  • /translate+x|y|z/i.test('translateX') returns true
  • /translate+x|y|z/i.test('translate') returns false
  • /translate+x|y|z/i.test('rotateX') returns false

So with other words, I need to know if the string is translateX or translateY or translateZ but I am not sure if I have / don't have to escape the + there. Also please DO suggest a better all round, cross-browser solution that can be shorter / more precise.

4
  • 3
    What are trying to achieve? What are the requirements? \+ matches a literal + and in your pattern, + is a quantifier allowing to match several e after translat. Commented Mar 7, 2016 at 12:52
  • I would assume that it's /translate[xyz]?/i what he means Commented Mar 7, 2016 at 12:58
  • Thanks for the input, so I basically want to know if the string is translateX or translateY or translateZ in a very short and efficient .test() call. Commented Mar 7, 2016 at 12:59
  • 1
    then /^translate[XYZ]$/.test(text) Commented Mar 7, 2016 at 13:04

1 Answer 1

1

I basically want to know if the string is translateX or translateY or translateZ in a very short and efficient .test() call.

You can use

/^translate[XYZ]$/

See the regex demo here.

The regex matches a string that is equal to translateX, translateY or translateZ.

  • ^ - start of string
  • translate - a literal character sequence
  • [XYZ] - either X, Y or Z ([ ... ] a character class where the single characters alternatives are listed)
  • $ - end of string

If you need to add multicharacter alternatives, use alternation:

/^translate(?:[XYZ]|3d)$/
           ^^^     ^^^^

This regex will match those 3 strings as above, or translate3d.

Sign up to request clarification or add additional context in comments.

5 Comments

Awesome, thank you for such a detailed answer/suggestion.
Glad it works for you. One note: if you need to make it case insensitive, add /i to the end: /^translate[XYZ]$/i.
Actually, how can I add 3d to the [XYZ] list?
Use alternation: /^translate(?:[XYZ]|3d)$/
Excellent, that worked perfect. I wish you were my friend forever :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.