-4

I have a string, and I don't know if it is more than 36 characters or not. If it is longer that 36 characters I only want the first 36 characters:

var longString = "sdfkjhs3 234kjh khjk 234kjh 234kj h23k423h4 23k4";
var templongString = longString.substring... ?

Edit

I was trying

var longString = "sdfkjhs3 234kjh khjk 234kjh 234kj h23k423h4 23k4";
var templongString = templongString.substring(longstring, 36);
tereško
  • 729
  • 1
  • 8
  • 16
  • 2
    Please do not rollback my edits. Your question has nothing to do with jQuery. – Paul Jan 15 '14 at 16:57
  • 3
    Because simply looking up the [substr](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr) method could have answered your question. – tenub Jan 15 '14 at 16:57
  • @Paulpro i was trying to delete question and by mistake rolled back your changes, sorry... – tereško Jan 15 '14 at 16:58
  • Consult the docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring – hunterc Jan 15 '14 at 16:58
  • Negative vote because you didn't specify [what you already tried](http://whathaveyoutried.com/). – BryanH Jan 15 '14 at 17:00

3 Answers3

5
var templongString = longString.substring(0, 36);

This will truncate the string to 36 characters.

James
  • 109,676
  • 31
  • 162
  • 175
1

You can do:

if(longString.length > 36) {
     var templongString = longString.substring(0, 36);
}
Paul
  • 139,544
  • 27
  • 275
  • 264
Felix
  • 37,892
  • 8
  • 43
  • 55
  • 1
    The `if` is redundant. If the string length is less than 36, `substring(0, 36)` [will return the entire string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring#Description). – BryanH Jan 15 '14 at 17:08
1

You can use the String.prototype.slice method (which also saves a few characters):

var newString = longString.slice(0, 36);

I personally prefer this implementation as it's expected behaviour aligns with Array.prototype.slice.

Todd Motto
  • 903
  • 6
  • 10
  • What browser are you testing in? The link you provided actually contradicts what you're saying except for the one case in Chrome 33 generally substr is faster (with long strings) – rorypicko Jan 15 '14 at 17:04