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 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); You can use slice to do this
string.slice(start,end) start would be ... it could be negative.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);
'elephant'.substr(-4)?