开发者

Why does this javascript helper return back an array?

function(obj){
 if(obj == undefined || obj == null){
   return '';
}

  var id = obj.match(/\d+$/);

  return id || '';
}

I have a DOM element that looks like:

id="some-text-123"

and I want the '123' part of the id to be returned when calling the above function.

other elements might be like:

id="123"
id="some-123"
id="some开发者_如何学C-ting-else-1"

I called this on an element that looked like "some-text-213"

and it seemed to return an array, I just want the id returned.


.match() returns an array.

That is where the array is coming from

See fiddle: http://jsfiddle.net/maniator/WnFYD/


The function .match() returns an array.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/match


The match method returns an array, the first item of which contains the entire matched text. Update your return statement to reflect this:

return id ? id[0] : '';


The match function returns an array, so your function returns an array if there's a match.


you might want to use a grouping parens in your regex

var matches = obj.match(/(\d+$)/);
if(matches.length > 0) {
  return matches[1];
}


Javascript's regex match returns an array of matched results. In all of your test cases, it will be an array with a single value in it, like ["123"] or ["1"]. If you had a test case like "123-abcd-456", match would return ["123", "456"].

If you are sure you only ever want the first match, you can do this:

var matches = obj.match(/\d+$/);
if(matches.length != 0) {
    return matches[0];
}

return '';


return id[0] ¦¦ '';

Will return the first match is that what you want?

Edit: sorry pipe char isn't working for me at the moment

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜