-2

I know there are methods to remove characters from the beginning and from the end of a string in Javascript. What I need is trim a string in such a way that only the last 4 characters remain.

For eg:

ELEPHANT -> HANT 1234567 -> 4567 
2
  • 2
    You mean 'elephant'.substr(-4)? Commented Oct 21, 2013 at 6:10
  • do you maybe want a substring? Commented Oct 21, 2013 at 6:10

4 Answers 4

3

String.prototype.slice will work

var str = "ELEPHANT"; console.log(str.slice(-4)); //=> HANT 

For, numbers, you will have to convert to strings first

var str = (1234567).toString(); console.log(str.slice(-4)); //=> 4567 

FYI .slice returns a new string, so if you want to update the value of str, you would have to

str = str.slice(-4); 
Sign up to request clarification or add additional context in comments.

2 Comments

just tried it and it works. @Nikhil Actually i just need to display the last 4. Not required to change the actual string.
I added a note either way :)
0

Use substr method of javascript:

var str="Elephant"; var n=str.substr(-4); alert(n); 

Comments

-1

You can use slice to do this

string.slice(start,end) 

3 Comments

down-vote as slice with negative number is better
@user2310289 This answer didn't make any assumptions about what start would be ... it could be negative.
Maybe an example can be given to show how this would be used
-1

lets assume you use jQuery + javascript as well.

Lets have a label in the HTML page with id="lblTest".

<script type="text/javascript"> function myFunc() { val lblTest = $("[id*=lblTest]"); if (lblTest) { var str = lblTest.text(); // this is your needed functionality alert(str.substring(str.length-4, str.length)); } else { alert('does not exist'); } } </script> 

Edit: so the core part is -

var str = "myString"; var output = str.substring(str.length-4, str.length); 

2 Comments

What was the reason for down-vote? I'd like to understand...
it wasn't me, but what happens if str is < 4 chars in length?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.