如何获得"年"来自jquery或javascript中的字符串值?

时间:2014-10-22 18:04:36

标签: javascript jquery

我得到了这样的字符串:

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

我正在尝试写一个这样的函数:

function getyear(val)
{
    return val;
}

所以,如果我传递string1,它应该给我" 2010",如果传递string2,它应该给我"现在"

如何使用jquery?还是java脚本?

6 个答案:

答案 0 :(得分:3)

使用正则表达式,例如:

/\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>

答案 1 :(得分:0)

也许你可以这样做:

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

这将返回找到的第一个int,如果找不到它,它将返回传递的值。这样它就会回归&#39;没有一年的时候,无论在弦中的哪个地方。您也可以通过“我想要的那一年是2010年”。它应该回归2010年。

答案 2 :(得分:0)

您可以使用:

&#13;
&#13;
string1 = "Feb 2010 "
string2 = "On Going"
string3 = "may 1990 "
string4 = "jun 1990 "
string5 = "On Going "

function getyear(val) {
    var newVal = "Now";
    return val == "On Going" ? newVal : val.substr(val.indexOf(' ') + 1);
}

console.log(getyear(string1)); //gives 2010
console.log(getyear(string2)); //gives Now
&#13;
&#13;
&#13;

请注意,如果没有空格则会返回完整字符串

答案 3 :(得分:0)

&#13;
&#13;
var string = "hello 2014";
var l = string.substr(string.length - 4);
if(l.charAt(l.length - 4) == '1' ||l.charAt(l.length - 4) == '2')
  alert(l.slice(-4));
else
  alert("Now");
  
&#13;
&#13;
&#13;

答案 4 :(得分:0)

这应该有效。使用reg exp

&#13;
&#13;
function myFunction( val) {
     // val = "year 2014";
    var patt1 = /[0-9]{4}/g;
    
   if ( str.match(patt1) )
        return ( str.match(patt1) );
   else
        return val;
    
}
&#13;
&#13;
&#13;

答案 5 :(得分:0)

我建议:

function getYear (str) {
    var year = (/\b\d{4}\b/).exec(str);
  return year === null ? 'Now' : year[0];
}

&#13;
&#13;
function getYear (str) {
    var year = (/\b\d{4}\b/).exec(str);
  return year === null ? 'Now' : year[0];
}

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

specimins.forEach(function (string, index) {
  console.log(index + ': ' + getYear(string));
});
&#13;
&#13;
&#13;

参考文献: