0

Here comes a simple question, for all those who know javascript. I made an application, which grabs the following code and puts it into a variable:

<div class="article-author">Af <span class="remove_from_bt_touch">:</span>Af Tho
mas S&oslash;gaard Rohde, Berlingske Nyhedsbureau<span class="section-time">&nbs
p;15. jan. 2012
               |
            </span>
<span class="section-category">Danmark</span>
</div>

Now, what I want is another variable, containing the DATE of the variable above. So it should be 15. jan. 2012.

How do I do that?

3
  • why do you need a variable that holds 16 jan instead of 15 jan from the data? Commented Apr 3, 2012 at 12:42
  • You might want to look for Regular Expressions in javascript. see this Commented Apr 3, 2012 at 12:44
  • Thanks! How should the regex look in my situation? Commented Apr 3, 2012 at 12:49

2 Answers 2

2

Don't really understand what you mean by "puts it in a variable" other than to say the markup is a string assigned to a variable like:

var m = '<div class="article-author">Af ' +
        '<span class="remove_from_bt_touch">:<\/span>' +
        'Af Thomas S&oslash;gaard Rohde, Berlingske' +
        ' Nyhedsbureau<span class="section-time">&nbsp;' +
        '15. jan. 2012 | <\/span>' +
        '<span class="section-category">Danmark<\/span><\/div>';

If that is the case, you can get the date (provided it is exactly in the format shown) using match with a regular expression:

var re = /\d\d?\. [a-z]{3}\. [0-9]{4}/;

alert(m.match(re)); // 15. jan. 2012       

However, if you mean it is markup in a page and you are trying to get the text in the span with class section-time, then you can use something like:

// Get all elements with class section-time, use DOM method, 
// querySelectorAll or some other means
var el, els = document.getElementsByClassName('section-time');

// Get the date out of each. Use a regular expression as there
// seems to be other stuff in there
var dates = [];
var re = /\d\d?\. [a-z]{3}\. [0-9]{4}/;

for (var i=0, iLen=els.length; i<iLen; i++) {
  el = els[i];
  dates.push((el.innerText || el.textContent).match[0]);
}

Or you could get all such dates in an array using match with the above regular expression on the innerHTML of a common parent element.

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

Comments

1
var date = $('.section-time').text();

Using jQuery of course.

1 Comment

Sorry, but the tool I am using dosen't support Jquery

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.