0

If we have a string, say

'1, 2, 3, 4'
'1, 2, 3 GO!'
'ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!'

then how do I recognize that its has numbers and return true?

I need it because while using,

if(input == input.toUpperCase())

if a number is entered this condition returns true, so need to add an elegant way to stop the numbers from passing this condition.

Edit1: The string is indeed comma separated, I already have googled ways that recognize non comma separated strings as numbers.

Edit2: Added more examples of what I need to pass.

5
  • 1
    alert('(1, 2, 3, 4)'.search(/\d/) !== -1); Commented Oct 5, 2014 at 18:39
  • Does regex meet your requirements? What other strings do you need to be able to parse? Commented Oct 5, 2014 at 18:39
  • @Brad Regex is my last resort, all alphabets, special characters and umlauts. Commented Oct 5, 2014 at 18:42
  • 1
    @PrakashWadhwani Why would regex be your last resort if it does exactly what you want? And, I'm saying that if you want to parse a wide variety of strings, you should provide more than one example in your question. Otherwise, it isn't clear what you're trying to do. Commented Oct 5, 2014 at 18:43
  • @Brad its classical problem called Bob, you can read about it here, jsfiddle.net/pzoc03vm and the tests that need to be passed are, jsfiddle.net/7yzfpor9 Commented Oct 5, 2014 at 18:45

1 Answer 1

1

Regular expressions are appropriate for this:

var str = "(1, 2, 3, 4)";
var containsNumber = /\d/.test(str);      // true

Here, \d is a regular expression that will match if your string contains a digit anywhere.


Ok, looks like you need to look for lowercase letters... If there's any lowercase letter it shouldn't be considered yelling.

var str = "(1, 2, 3, 4)";
var containsLowercaseLetters = /[a-z]/.test(str);      // false

This will only work for latin letters though. In your case, it may be simpler to just state:

var isYelling = (input == input.toUpperCase()) && (input != input.toLowerCase());
Sign up to request clarification or add additional context in comments.

4 Comments

Ok, although it works with numbers only, but I need to also check if there is an alphabet with them, then it has to fail the test.
@PrakashWadhwani Update your question with an appropriate test case.
Updated. Beware of asking X-Y problems in the future ;)
Aha! Exactly what I was looking for, simple and elegant without any confusing regex, toLowerCase beautifully rejects numbers, I wish I had thought that myself! Thanks Lucas!

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.