Click here to Skip to main content
15,908,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please, how can I extract the last three(3) characters for a changing string in javascript?
lets say:
I have: var name;

name can alsways changed if it is reassigned; I want to get the last three(3) from the right. example if name = "JAMES", I want to get "MES"

Thanks.
Posted

 
Share this answer
 
v2
Comments
Bassofa 9-Feb-11 13:02pm    
Thanks for your response; I have tried that and it doesn't seem to work; I did that earlier..
Nish Nishant 9-Feb-11 13:02pm    
Post your code.
Sergey Alexandrovich Kryukov 9-Feb-11 13:06pm    
Oh, again... My 5, enough said.
--SA
Try Javascript substring method[^].

BTW, AFAIR, it's not crossbrowser supported. So, do check/use it accordingly Looks like it is supported by all browsers now[^].

Hmmm, try this:
name.substr(-3); // should return MES
 
Share this answer
 
v3
Comments
Sergey Alexandrovich Kryukov 9-Feb-11 13:08pm    
What, "substr" can be not cross-browser? Hm. What should be?
(My 5 anyway).
--SA
Sandeep Mewara 9-Feb-11 13:11pm    
Quick Google gave this blog entry: http://www.bloggingdeveloper.com/post/substring-vs-substr-The-Difference-Between-JavaScript-String-Functions.aspx

Last line says, its not. Will share if I come across an authenticated source.

EDIT:
This link says, it all supported now: http://solidlystated.com/scripting/difference-between-javascript-substring-and-substr/
Yep!
Sandeep Mewara 9-Feb-11 13:11pm    
And surely, it should had been cross-browser, if not, strange!
Sergey Alexandrovich Kryukov 9-Feb-11 16:33pm    
Exactly, that's why I asked. Thank you.
--SA
Check out this web page for substrings method;
http://www.electrictoolbox.com/javascript-substr/[^]

So maybe at first you can get the string length by using name.length and then use the substring method.
 
Share this answer
 
Like everyone said, you need substring, but you need to tell it where you want to start. In your case it is length-3


var name = "JAMES";
name.substring(name.length-3);
 
Share this answer
 
Comments
#realJSOP 9-Feb-11 13:21pm    
Proposed as answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900