user978905
user978905

Reputation: 5527

Keep only first n characters in a string?

Is there a way in JavaScript to remove the end of a string?

I need to only keep the first 8 characters of a string and remove the rest.

Upvotes: 512

Views: 479638

Answers (7)

Shad
Shad

Reputation: 15471

const result = 'Hiya how are you'.substring(0,8);
console.log(result);
console.log(result.length);

You are looking for JavaScript's String method substring

e.g.

'Hiya how are you'.substring(0,8);

Which returns the string starting at the first character and finishing before the 9th character - i.e. 'Hiya how'.

substring documentation

Upvotes: 806

Wasim Karani
Wasim Karani

Reputation: 8886

Use substring function
Check this out http://jsfiddle.net/kuc5as83/

var string = "1234567890"
var substr=string.substr(-8);
document.write(substr);

Output >> 34567890

substr(-8) will keep last 8 chars

var substr=string.substr(8);
document.write(substr);

Output >> 90

substr(8) will keep last 2 chars

var substr=string.substr(0, 8);
document.write(substr);

Output >> 12345678

substr(0, 8) will keep first 8 chars

Check this out string.substr(start,length)

Upvotes: 25

KooiInc
KooiInc

Reputation: 122986

You could use String.slice:

var str = '12345678value';
var strshortened = str.slice(0,8);
alert(strshortened); //=> '12345678'

Using this, a String extension could be:

String.prototype.truncate = String.prototype.truncate ||
  function (n){
    return this.slice(0,n);
  };
var str = '12345678value';
alert(str.truncate(8)); //=> '12345678'

See also

Upvotes: 102

pimvdb
pimvdb

Reputation: 154958

You can use .substring, which returns a potion of a string:

"abcdefghijklmnopq".substring(0, 8) === "abcdefgh"; // portion from index 0 to 8

Upvotes: 1

Sahil Muthoo
Sahil Muthoo

Reputation: 12506

var myString = "Hello, how are you?";
myString.slice(0,8);

Upvotes: 8

Mike Christensen
Mike Christensen

Reputation: 91716

You could try:

myString.substring(0, 8);

Upvotes: 8

Saket
Saket

Reputation: 46157

Use the string.substring(from, to) API. In your case, use string.substring(0,8).

Upvotes: 2

Related Questions