1

I am really struggling to find a solution to this i want to find every instance of a number in a paragraph of text.

<div id='text'>
this is the number 20px and this is the number 100 and this is the number 10.
</div>

So i want to take this and have it ouput the following. 20 100 10

<script type="application/javascript">
        $(document).ready(function() {

        var text = $('.text').text().toString().search( new RegExp( /^[0-9]+$/ i ) );

        alert(text);    

        });                  
        </script>

from the alert i just want it to output the numbers in the text i.e 20 100 10, i now this is way off but any help to put me in the right direction i am banging my head against a wall, thanks.

3
  • Your pattern should be /\d+?/, can't think of the right funcs right now. Commented Nov 23, 2010 at 17:44
  • 1
    If there are negative numbers(-100) should you capture -100 or 100? Commented Nov 23, 2010 at 17:49
  • great point Mikael I modified my regexp for negative and decimal numbers too. :) Commented Nov 23, 2010 at 17:52

3 Answers 3

1

I don't know where you would replace anything, but to find all numbers, something like this is enough:

// results an array of numbers
var results = $('#text').text().match(/\d+/g);
Sign up to request clarification or add additional context in comments.

3 Comments

Right, but won't match single digit numbers
Zlatev, + quantifier means 1 or more digits
/\d+/.test("1") returns true, because + means one or more digits
1
$('#text').html().match(/\-?\d+(\.\d+)?/g).join(' ')

creates a string with all numbers found inside the div element.

to get an array of all numbers found just remove the .join() method

Plase note that you have 'text' as id of your element, so you need refer to it as $('#text') and not as $('.text')

Comments

1

If you use this:

var txt = $( '#text' ).html().match(/\d+/g)

it will give you an array of the numbers

1 Comment

Sorry, Harmen -- had this open and posted before I saw your response.

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.