views:

39

answers:

2

I have a variable set to retrieve the id of a specific element which is "PubRecNum-1" (the number is also variable and will change depending on the record number). What I'm needing is a way to only take the first 3 letters of the variable "Pub" (needed for comparison purposes).

Any ideas?

+2  A: 

You can get those letters using substring() or slice():

var str = "PubRecNum-1";
alert(str.substring(0, 3)); // -> "Pub"
alert(str.slice(0, 3)); // -> "Pub"
Andy E
great thank you!
sadmicrowave
so can I say if(str.substr(0,3)=="Pub"){DO SOMETHING});????
sadmicrowave
@sadmicrowave: yes, that would work fine. As a general rule I would stick to using `slice` or `substring`, `substr` isn't part of the ECMAScript standard and its implementation differs between browsers.
Andy E
thanks I've changed it to substring
sadmicrowave
+2  A: 

Javascript's substring() or substr() is used for exactly this

Charlie boy
Note that the `substr()` is not part of the ECMAScript standard and its implementation varies between browsers. Although `(0, 3)` as arguments would work the same across implementations, I prefer to avoid `substr()` altogether.
Andy E
Didn't know that. Thanks! I suppose you learn something every day ...
Charlie boy