0

I am having a div in HTML. And it has this value : "Showing 1 to 25 of 31 entries". Where the number 31 can vary. I want to get this number 31 in some variable using javascript. What is best way to do it ?

Javascript :

var x = document.getElementById('available-questions_info').innerHTML;
alert("CURRENT VALUE IS "+x);

HTML :

<div class="dataTables_info" id="available-questions_info">Showing 1 to 25 of 31 entries</div>
4
  • substr if the string length and format is fixed str.substr(str.indexOf('of ') + 3, 2); but this is not flexible. Better approach will be regex /of\s(\d+)/ Commented Oct 3, 2015 at 9:38
  • @Tushar Format is fixed. But How to use substr ? It can be like "Showing 26 to 31 of 31 entries. length is not fixed if you see. Some regex might help I guess Commented Oct 3, 2015 at 9:40
  • @Tushar Can you add some code how to use regex ? Commented Oct 3, 2015 at 9:40
  • var num = x.match(/of\s(\d+)/)[1]; // 31 Commented Oct 3, 2015 at 9:42

3 Answers 3

1

You can use a regular expression to capture it:

test("Showing 1 to 25 of 31 entries");
test("Showing 1 to 25 of 53 entries");
test("Showing 1 to 1 of 1 entry");

function test(str) {
  var rex = /(\d+) (?:entry|entries)/;
  var match = rex.exec(str);
  if (match) {
    snippet.log(match[1]); // "31", etc.
  } else {
    snippet.log("Didn't match");
  }
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

/(\d+) (?:entry|entries)/ means "Capture one or more digits followed by a space and the word 'entry' or 'entries'". The captured text is available as entry #1 in the resulting match array.

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

Comments

0
var x = "Showing 1 to 25 of 31 entries";
var d = x.match("of (.*) entries");
alert(d[1]);

Comments

0

The simple solution will be like this keeping aside efficiency.

var arr = x.split(' ');

var num = arr[5];

The number you want to get will be in variable named 'num'.

I am answering by thinking that you have already got the string using getElementById function in a variable named 'x'.

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.