1
var text = "rating-1-gray-3-blue";

i want to get value 13

how can i do this . basically i want to get all integers inside a string .

i tried with parseInt , but it returns int when the integer value is at the beginning of the string

thanks in advance

1
  • All integers in a string would result in [1, 3] for your example Commented Jan 23, 2013 at 11:45

2 Answers 2

4

You may use regular expressions:

var result = +text.replace(/\D/g, "");  // 13
Sign up to request clarification or add additional context in comments.

6 Comments

.. and reversed: var result = +text.match(/\d/g).join('');
@jAndy if only creating a new array makes any sense :)
it does. It's even slightly faster for me (Chrome). jsperf.com/regexp-vs-regexp-vs-regexp
@jAndy Any ideas why? replace does extra internal string iteration(s), while match not?
I honestly don't know the reason. Might even be because the different regexp matches \D vs. \d.
|
2
var result=text.replace(/[^0-9]/g, ''); 

This removes all non 0-9 values from your string

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.