开发者

How to Fetch Last string using jQuery?

Let's say I have a string like this

Hello World, I am xyz, How are you ?

And I need all the characters in the string that comes after last comma. Which is here

How are you?

How can I do this ?

Note : Here space in the beginning should not come.

Also I need the remaining string into another开发者_JAVA百科 variable which will be

Hello World, I am xyz

Note: here comma in the end should not come.


You can do that with a simple regex:

s   = 'Hello World, I am xyz, How are you ?';
hay = s.replace(/.*,/, '');
// " How are you ?"

Or, if you want to take care of the leading space at the same time:

s   = 'Hello World, I am xyz, How are you ?';
hay = s.replace(/.*,\s*/, '');
// "How are you ?"

If you want the first part and the "How are you ?" part, then you could use match instead of replace:

var m = s.match(/^(.*),\s*(.*)$/);
// m[1] is "Hello World, I am xyz"
// m[2] is "How are you ?"


you can do with normal javascript -

var a= "Hello World, I am xyz, How are you ?"
alert(a.substring(a.lastIndexOf(',')+1,a.length));


No jquery required but i would use the trim function in conjunction with the following:

var str = 'Hello World, I am xyz, How are you ?'

jQuery.trim(str.substring(str.lastIndexOf(',') + 1));


you dont really need jquery for that, maybe just for the CSS-selector to find the text, but you can use normal Javascript like split and splice to find the last text: http://jsbin.com/ibugob/2/edit


Don't think it can be done with jQuery, but simple Javascript will do the trick.

var phrase = "Hello World, I am xyz, How are you ?";
var splitPhrase = phrase.split(",");

var lastElement = splitPhrase[splitPhrase.length - 1];


JavaScript strings actually have a .split() function, so you won't need jquery at all:

var str = "Hello world, I am xyz, How are you?";
var parts = str.split(",");

// That just gave you an array
// ...Now find the last element:
var result = parts[parts.length - 1];


Probably, like this also.

var a = "Hello World, I am xyz, How are you ?"
alert(a.split(',')[2]);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜