Get first value before comma

Asked

Viewed 209 times

2

Hello I’m having difficulty storing the value of the day that precedes the comma:

<span id="organizerContainer-date">Novembro 3, 2018</span>

I would like to store this value to do some things. If someone has done this before you could let me know what it would be like to do it using jquery ?

2 answers

3

You don’t need jQuery for this, with Javascript it is simple and you can do so, assuming that the date format is always the same:

var span = document.getElementById("organizerContainer-date");
var nr = span.innerHTML.split(/[\s,]/).filter(Boolean)[1];
console.log(nr); // 3
<span id="organizerContainer-date">Novembro 3, 2018</span>

  • Hello Sergio, can you explain the logic behind filter(Boolean) and why not directly split(...)[1] ?

  • @Isac for the question example is not necessary, but my experience is that there are always variations in the input string. If for example there is a space before the month name, then the code would fail. Or an extra space between words/number, then it would also fail. Just as the accepted answer would also fail. So I use .filter(Boolean) which basically removes empty positions in the array that the split creates. It’s clear? It might be interesting to add this to the answer?

  • 1

    Yes I had already realized that you were removing the voids just not to see why. I think it actually makes the solution better and more robust. Thank you for the reply

0


Using jQuery:

dia_ = $('#organizerContainer-date').text().split(' ')[1].replace(/\D/g, '');
console.log(dia_); // retorna 3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="organizerContainer-date">Novembro 3, 2018</span>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.