-4

How can I create a regex for that returns true if it has only numbers and '+' basically 0-9 & +. Using javascript or jQuery.

j08691
  • 197,815
  • 30
  • 248
  • 265
Sam B.
  • 2,193
  • 7
  • 31
  • 69

1 Answers1

2
  • Regex for plus anywhere: /^[0-9+]+$/
  • Regex for plus only infront: /^\+?[0-9]+$/

What it does:

  • ^ Matches the beginning of the string
  • [0-9+] Matches 0123456789+
  • + Matches one or more
  • $ Matches the end of the string

Other version:

  • \+? Matches zero or one plus signs in the front

Maybe try regexr for future regex development.

How to test in code:

function isOnlyNumber(str) {
  return /^[0-9+]+$/.test(str);
}
Le 'nton
  • 346
  • 3
  • 22