0

I am trying to implement a function in Javascript that verify a string. The pattern i must to do is contain only digits charactor, *, # and +. For example:

+182031203
+12312312312*#
+2131*1231#
*12312+#
#123*########

I tried alot of thing like

/^[\d]{1,}[*,#,+]{1,}$

but it's doesn't work. I am not sure that i understand good in regex. Please help.

1
  • You could attempt to match [^\d*#+] and negate the results; that is, the string contains only the permissible characters if and only if this match fails (assuming the string is not empty). Commented Oct 28, 2021 at 7:32

3 Answers 3

2

I think you want the pattern ^[0-9*#+]+$:

var inputs = ["+182031203", "+12312312312*#", "+2131*1231#", "12312+#", "#123########"];
for (var i=0; i < inputs.length; ++i) {
    console.log(inputs[i] + " => " + /^[0-9*#+]+$/.test(inputs[i]));
}

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

1 Comment

^[0-9*#+]*$ if a string could be empty.
0

Using Regex101

/^[0-9\*\#\+]+$/g

0-9 matches a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive) * matches the character * with index 4210 (2A16 or 528) literally (case sensitive) # matches the character # with index 3510 (2316 or 438) literally (case sensitive) + matches the character + with index 4310 (2B16 or 538) literally (case sensitive)

Comments

0

Try this regular expression:

const rxDigitsAndSomeOtherCharacters = /^(\d+|[*#]+)+$/;

Breaking it down:

  • ^ start-of-text, followed by
  • ( a [capturing] group, consisting of
    • \d+ one or more digits
    • | or...
    • [*#+]+ one ore more of *, # or +
  • )+, the [capturing] group being repeated 1 or more times, and followed by
  • $ end-of-text

Comments

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.