Skip to main content
Ben Nadel at CFUNITED 2008 (Washington, D.C.) with: Nafisa Sabu
Ben Nadel at CFUNITED 2008 (Washington, D.C.) with: Nafisa Sabu

Using Slice(), Substring(), And Substr() In Javascript

By
Published in Comments (13)

In the book, Eloquent Javascript: A Modern Introduction to Programming, Marijn Haverbeke takes the reader through a good number of string-parsing examples. And, in his examples, Haverbeke makes frequent use of the String method, slice(). When I think of slice(), I think of extracting portions of a Javascript array; I don't think I was even aware that the Javascript String prototype had a slice() method. To clear up my own confusion and misconceptions, I wanted to take a quick look at the various ways in which Javascript allows for partial string extraction.

From what I can see, there are three primary methods for substring extraction:

  • String.slice( begin [, end ] )
  • String.substring( from [, to ] )
  • String.substr( start [, length ] )

In all cases, the second argument is optional. If it is not provided, the substring will consist of the start index all the way through the end of the string. For both the slice() and substring() methods, the second argument is exclusive; that is, the resultant substring will not contain the character at the final index.

Let's take a look as these three approaches in action:

<!DOCTYPE html>
<html>
<head>
	<title>Extracting Substrings In Javascript</title>

	<script type="text/javascript">


		// For these demos, let's create a numbered string so that
		// we can easily see where the indexes come into play with
		// all of the substring methods.
		//
		// NOTE: We are starting at zero since Javascript is all
		// zero-based.
		var numbers = "0123456789";


		// -------------------------------------------------- //
		// -------------------------------------------------- //


		// String.slice( begin, end )

		// Let's start by using both begin and end.
		console.log(
			"slice( 3, 7 ) :",
			numbers.slice( 3, 7 )
		);

		// What happens when we start with a negative number.
		console.log(
			"slice( -7, 7 ) :",
			numbers.slice( -7, 7 )
		);

		// What happens when we use two negative numbers.
		console.log(
			"slice( -7, -3 ) :",
			numbers.slice( -7, -3 )
		);

		// What happens when we omit the last argument.
		console.log(
			"slice( 3 ) :",
			numbers.slice( 3 )
		);

		// And with the negative, end-relevant index.
		console.log(
			"slice( -7 ) :",
			numbers.slice( -7 )
		);

		// If the index is out of range, it returns the empty string.
		console.log(
			"slice( 100, 101 ) :",
			numbers.slice( 100, 101 )
		);


		// -------------------------------------------------- //
		// -------------------------------------------------- //


		// String.substring( from, to )

		// Let's start by using both begin and end.
		console.log(
			"substring( 3, 7 ) :",
			numbers.substring( 3, 7 )
		);

		// What happens when we start with a negative number.
		console.log(
			"substring( -7, 7 ) :",
			numbers.substring( -7, 7 )
		);

		// What happens when we use two negative numbers.
		console.log(
			"substring( -7, -3 ) :",
			numbers.substring( -7, -3 )
		);

		// What happens when we omit the last argument.
		console.log(
			"substring( 3 ) :",
			numbers.substring( 3 )
		);

		// And with the negative, end-relevant index.
		console.log(
			"substring( -7 ) :",
			numbers.substring( -7 )
		);

		// If the index is out of range, it returns the empty string.
		console.log(
			"substring( 100, 101 ) :",
			numbers.substring( 100, 101 )
		);


		// -------------------------------------------------- //
		// -------------------------------------------------- //


		// String.substr( start, length )

		// Let's start by using both start and length
		console.log(
			"substr( 3, 4 ) :",
			numbers.substr( 3, 4 )
		);

		// What happens when we start with a negative number.
		console.log(
			"substr( -7, 4 ) :",
			numbers.substr( -7, 4 )
		);

		// What happens when we omit the last argument.
		console.log(
			"substr( 3 ) :",
			numbers.substr( 3 )
		);

		// And with the negative, end-relevant index.
		console.log(
			"substr( -7 ) :",
			numbers.substr( -7 )
		);

		// If the index is out of range, it returns the empty string.
		console.log(
			"substr( 100, 1 ) :",
			numbers.substr( 100, 1 )
		);


	</script>
</head>
<body>
	<!-- Intentionally left blank. -->
</body>
</html>

When we run the above code, we get the following console output:

slice( 3, 7 ) : 3456
slice( -7, 7 ) : 3456
slice( -7, -3 ) : 3456
slice( 3 ) : 3456789
slice( -7 ) : 3456789
slice( 100, 101 ) :

substring( 3, 7 ) : 3456
substring( -7, 7 ) : 0123456
substring( -7, -3 ) :
substring( 3 ) : 3456789
substring( -7 ) : 0123456789
substring( 100, 101 ) :

substr( 3, 4 ) : 3456
substr( -7, 4 ) : 3456
substr( 3 ) : 3456789
substr( -7 ) : 3456789
substr( 100, 1 ) :

As you can see, the slice() and substring() methods are roughly the same; the only difference is that the slice() method can accept a negative index, relative to the end of the string. Should you try to use a negative index in substring(), it seems to be relative the beginning of the string (and therefore is out-of-bounds).

The substr() method can use a negative index; but, rather than using a to-argument, it uses a length-argument. This can be especially useful if you know the length of the substring ahead of time and don't want to perform any superflous math to calculate the necessary indices.

NOTE: According to W3Schools, using a negative index in substr() does not work with Internet Explorer (IE).

I can't see a reason to use the substring() method. It appears to be a less-robust version of the slice() method. If you know the indices, use slice(); if you know the length, use substr(). Unless I'm missing something subtle, the decision making seems to be fairly straightforward.

Want to use code from this post? Check out the license.

Reader Comments

7 Comments

I'm with you -- I never even noticed the string slice() method before for some reason. Thanks for pointing it out! I've always just used the substring method, but the ability to use negative indexes could definitely come in handy.

There are probably cases where you might want any negative number to just be treated the same as 0, so the substring method could still be useful, though I don't have a particular use case in mind.

3 Comments

This is good information. I was mistakenly using substring since it was named the same as other languages but since I was expecting the behavior from substr I had to perform a calculation to pass the correct arguments. Thanks for this!

15,902 Comments

@David,

The negative offset is definitely a cool concept. I see some languages support that for array-addressing as well. I've not had the chance to play with it too much (as ColdFusion doesn't have this concept); but, I am sure it can be very useful for the last element (-1).

@Andy,

Good point - and I think other languages truly treat strings as arrays of characters at the core.

@Rob,

No problem - yeah, using length is typically easier than having to determine the appropriate the end index. Glad to help!

2 Comments

I think in this topic, we have to consider the split() function also. The split() method,
breaks the string where the separator(delimiter) occurs and returns the new strings in an array.

syntax: string.split(separator, limit)

example:

<script type="text/javascript">

var newstring = "abcdefg";
var cutstring = newstring.split("d");

</script>

Here the output of cutstring[0] will be abc and cutstring[1] will be efg. d is the delimiter here and so it won't appear in our output. Please note that limit is an optional one(integer) an it specifies the number of splits.

2 Comments

One thing to be aware of is that substr() is not part of the ECMAScript standard, where-as substring() and slice() are. So your mileage may vary with substr() (as noted that IE does not support negative values).

3 Comments

The ECMASript site has documentation describing substr on page 234 of http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

So I guess substr is part of their standard. Although I acknowledge the IE bug, which can be fixed like so:

// only run when the substr function is broken
if ('ab'.substr(-1) != 'b')
{
/**
*  Get the substring of a string
*  @param  {integer}  start   where to start the substring
*  @param  {integer}  length  how many characters to return
*  @return {string}
*/
String.prototype.substr = function(substr) {
	return function(start, length) {
	// did we get a negative start, calculate how much it is from the beginning of the string
	if (start < 0) start = this.length + start;
	 
	// call the original function
	return substr.call(this, start, length);
	}
}(String.prototype.substr);
}

source: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substr

2 Comments

@Chris...

So I guess substr is part of their standard

Nope... It's specifically called out by the ECMAScript standard as not being part of the standard. It is described in a "compatibility" annex to the standard (rather than being part of the standard). The section containing the description of substr() states:

Some implementations of ECMAScript have included additional properties for some of the standard native objects. This non-normative annex suggests uniform semantics for such properties without making the properties or their semantics part of this standard. (emphasis mine)

1 Comments

I am learning java script from professional coursework writers online and they are guiding me well about the uses of java script.
these tips are very helpful for me specially [ String.substr( start [, length ] ) ]
this part...
Thanks!

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
Ben Nadel