GitCoder
GitCoder

Reputation: 121

Getting part of string using javascript

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>

Upvotes: 0

Views: 41

Answers (3)

Umair Farooq
Umair Farooq

Reputation: 1704

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'.

Upvotes: 0

Adriansyah
Adriansyah

Reputation: 124

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

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074028

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.

Upvotes: 1

Related Questions