28

How can I get the first three letters of a string in JQuery?

For example: Turn cat1234 to cat

Shah
  • 505
  • 1
  • 5
  • 12
  • You can use `charAt()` for it works on IE, Chrome, Firefox, Safari and Opera. [Here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt) – rhavendc Apr 21 '16 at 08:12
  • 2
    A question that had 24 up votes and has 4 replies and 67 up votes is not constructive? – Fernando Kosh Feb 26 '19 at 18:36

4 Answers4

55

No jQuery needed! Just use the substring method:

var name = "cat1234"

var variable2 = name.substring(0, 3);
X-Factor
  • 2,067
  • 14
  • 18
20

Use .slice(start, end) with start and end values:

var str = 'cat1234';
document.body.innerHTML = str.slice(0, 3);

With javascript you can use a regular expression with .match() method to exclude the number and get the string value.

var str ='cat1234',
    rg = /[a-zA-Z]+/g,
    ns = str.match(rg);

document.body.innerHTML = ns[0];
Jai
  • 74,255
  • 12
  • 74
  • 103
7

you could also do:

var str = "cat1234";
console.log( str.substr(0, 3));
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
3

Use substring():

"cat1234".substring(0,3);

It means "get all the characters starting at position 0 up to position 3".

Please note this is not a JQuery function, it's plain Java Script.

kamituel
  • 34,606
  • 6
  • 81
  • 98