Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get "year" from string values in jquery or javascript?

i got the string like this :

string1 = "Feb 2010 " 
string2 =  "On Going"
string3 =  "may 1990 "
string4 = "jun 1990 "
string5 =  "On Going "

i am trying to write one funcation like this :

function getyear(val)
{
    return val;
}

so if i pass string1 , it should give me "2010", and if pass string2 ,it should be give me "Now",

how it possible using jquery? or java script?

like image 787
delm ric Avatar asked May 29 '26 05:05

delm ric


2 Answers

Use a regular expression such as:

/\d{4}/.test(val) ? val.replace(/^[^\d]*(\d{4}).*$/, '$1') : 'Now';

var string = [ "Feb 2010 ", "On Going", "may 1990 ", "jun 1990 ", "On Going "];

function getyear(val)
{
    return /\d{4}/.test(val) ? val.replace(/^[^\d]*(\d{4}).*$/, '$1') : 'Now';
}

$.each( string, function(i,v) {
  $('.out').append( (i+1) + ':\t' + getyear( v ) + '\n');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre class="out"></pre>
like image 136
PeterKA Avatar answered Jun 01 '26 15:06

PeterKA


Maybe you could do something like this:

function getyear(val){
    var split = val.split(" ");
    for (i = 0; i < split.length; i++){
        if(parseInt(split[i], 10)) return split[i];
    }
    return val;
}

This will return the first int found, and if it can't find one it will return the passed value. That way it returns 'on going' when there is no year, no matter where in the string. You can also pass 'The year I want is 2010' and it should return 2010.

like image 31
somethinghere Avatar answered Jun 01 '26 13:06

somethinghere



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!