admin管理员组

文章数量:1291098

I have a dynamically formed string like - part1.abc.part2.abc.part3.abc

In this string I want to get the substring based on second to last occurrence of "." so that I can get and part3.abc

Is there any direct method available to get this?

I have a dynamically formed string like - part1.abc.part2.abc.part3.abc

In this string I want to get the substring based on second to last occurrence of "." so that I can get and part3.abc

Is there any direct method available to get this?

Share Improve this question asked Nov 5, 2013 at 5:03 OkkyOkky 10.5k15 gold badges77 silver badges123 bronze badges 1
  • Are the lengths of each part dynamic? Or are they known? – William Riley Commented Nov 5, 2013 at 5:08
Add a ment  | 

2 Answers 2

Reset to default 8

You could use:

'part1.abc.part2.abc.part3.abc'.split('.').splice(-2).join('.'); // 'part3.abc'

You don't need jQuery for this.

Nothing to do with jQuery. You can use a regular expression:

var re = /[^\.]+\.[^\.]+$/;
var match = s.match(re);
if (match) {
  alert(match[0]);
}

or

'part1.abc.part2.abc.part3.abc'.match(/[^.]+\.[^.]+$/)[0];

but the first is more robust.

You could also use split and get the last two elements from the resulting array (if they exist).

本文标签: javascriptGet Second to last character position from string using jQueryStack Overflow