Get the 3 rightmost charachters from a string

I need to get the 3 rightmost charachters from a string, like the vb function Right(string,3) but I don’t know how to do this in javascript.


  function right(str, chr)
  {
	return str.slice(myString.length-chr,myString.length);
  }
  function left(str, chr)
  {
	return str.slice(0, chr - myString.length);
  }
  myString = new String('I need to get the 3 rightmost charachters from a string, like the vb function Right(string,3) but I don\\'t know how to do this in javascript.');
  alert( right(myString, 12) );
  alert( left(myString, 6) );
 
 

this will return “javascript.” & “I need”, hopeflly these function will be a bit more usefull to you.

You could also use substr like this:
<script language=“JavaScript”>
function right(str,chr)
{
return newstr=str.substr(str.length-chr,str.length)
}
function left(str,chr)
{
return newstr=str.substr(0,chr)
}
var mystring=“this is a string”
alert(right(mystring,3));
alert(left(mystring,3));
</script>

Andrew, there’s better ways to manipulate slice()

function right(str, chr)
{
return str.slice( -( chr ) );
}
function left(str, chr)
{
return str.slice( 0, chr );
}

Of course, if I was applying these, I’d make methods…

String.prototype.right = function( qty )
{
return this.slice( -( qty ) );
}
String.prototype.left = function( qty )
{
return this.slice( 0, qty );
}

Of course, I’m not a big fan of any function/method that just allows a slightly different interface to existing methods. I’d just stick with using slice()

I agree, but for simplicity I just wrapped it into a small function, so it is actually like the left() & right() vb function, which [b]claus erik[/b] seems to be more familiar with.