JavaScript SubString, Substr And Slice Methods Example

Last Updated on by in JavaScript

Understand JavaScript SubString

JavaScript substring, slice and substr are popular JavaScript methods to extract a substring from a string.

When it comes to any application, data manipulation is a crucial aspect of data manipulation. As we all know, popularity and demand for JavaScript have risen over the years. JavaScript is gaining more market share as we speak.

The demand for JavaScript to parse and extract data has increased.

We have already mentioned JavaScript substring, slice and substr, native members of the String object, which we use to extract sub-strings. Moreover, this extraction is done by character position. These members extract substrings based on a length and start position.

Yes, on principle, these 3 members behave in the same manner. However, their subtle differences you need to consider.

slice() Method Example in JavaScript

slice(startIndex[, endIndex]):It returns the string between beginIndex and endIndex. Here it will return as a new string.

// Syntax: string.slice(startIndex [, endIndex])

var string1 = "How cool and delicious it was!";

console.log(string1.slice(4,9))

// Output: 'cool'

substr() Method Example in JavaScript

substr(start[, length]): It returns the string starting from start index until the number of character specified in length parameter.

// Syntax: string.substr(start [, length])

var string2 = "The water was cool and had a metallic taste.";

console.log(string2.substr(3,7));

// Output: 'water'

substring() Method Example in JavaScript

substring(indexStart[, indexEnd]): It returns the string between the indexStart and indexEnd. Alternatively, it returns the end of the string.

// syntax: string.substring(start [, stop])

var string3 = "Nowadays, the social reformer is cool and hip!";

console.log(string3.substring(4,8));

// Output: 'days'

How to Deal with Negative Numbers using SubString, Substr And Slice Methods in JavaScript?

What if you pass an invalid value or negative numbers as parameters? rules are in place to deal with such scenarios. What if you pass a negative number via slice? In this case, it subtracts the number from the length of the string.

Negative number examples for string methods

var string = "Hello this is test";

string.substring(-4);
// "Hello this is test"

string.substr(-4);
// Output: "st"

string.slice(-4); 
// Output: "test"

It’s little different in the case of JavaScript substring. JavaScript substring will be converting all the negative numbers. Same will happen in the case of all the values from NaN to 0. Index indexStart has a bigger value compared to indexEnd, and then the values will be swapped. When you pass equal values, you will get an empty string as output.

Now let’s see the case of substr. When we pass a negative number, it will be converted to zero. In case the length or start parameters have NaN, then it will be converted to zero. In case you pass a negative number as a start, an index will be set to the string length minus value.

Work with Fixed Data String using JavaScript Substring, Slice & Substr Methods.

When it comes to a lot of IT systems, flat data files are standard. When we speak of file formats, we consider them the lowest common denominator. You will come across plenty of field delineators like commas or tabs. In some cases, fixed width rows are present too in text files.

As the consumer, you have got a clear idea about the number of characters present in each field. Let’s assume that a row is supposed to have 300 characters whereas a filed named ‘name’ takes the first forty characters. When you don’t use a character, you will pad it with space.

To extract the name field, you may use any of the three standard methods.

// Examples
dataRecord.substring(0,40);

dataRecord.slice(0, 40);

dataRecord.substr(0,40);

In the example that I have used, I just took a sentence and inserted the name “Tony Stark” at the very start. Then I added the remaining characters with spaces. To trace it without any difficulty, I chose ‘N’ as the last character. We hope that you have got a fair idea as for how we extract a string with all 3 methods.

As you can see in the below example output, all 3 extraction methods return the same substring in JavaScript. We have the same parameters in all 3 examples, and the name field is the very first ‘field’.

// Examples

var dataRecord = "Tony Stark                   N"

dataRecord.substring(0, 40);
// Output: "Tony Stark                   N"

dataRecord.slice(0, 40);
// Output: "Tony Stark                   N"

dataRecord.substr(0,40);
// Output: "Tony Stark                   N"

Well, now let’s examine the next field named, place. We are going to find it interesting. The place field can accommodate 30 characters. If we are to use the same methods with the same parameters, we will get the following output:

// Examples

var dataRecord = "Tony Start                    New York           H"


dataRecord.substring(30, 20);
// Output: "          "


dataRecord.substr(30, 20);
// Output: "New York           H"


dataRecord.slice(30, 20);
// ""


dataRecord.substring(30, 50);
// Output: "New York           H"


dataRecord.slice(30, 50);
// Output: "New York           H"

Well, we plan to pass values 30 and 20 for start index and field length respectively. As you can see in the above example, the only substr seems to work in this case.

Now we will see the case of the slice. Again it’s different. Given 30>20, it is going to return an empty string as a substring. From what we have learnt about the slice, it is meant to return to an empty string when we pass a value like this.

When we pass values 30 and 20 to JavaScript substring, the values will be swapped. Also, as output, you will get characters between positions 20th and 30th. How to fix this? You need to pass 30 as start index and 50 as the last index.

As you can see, slice behaves like JavaScript substring in this case. Therefore, we get the right output when we pass 30 and 50 as parameter values.

Yes, the key takeaway is that slice and substring are similar. The significant difference is that the slice can accept a negative number.

In the case of a slice, negative numbers will be converted to zero in the substring.

Summary

Well, all three JavaScript String methods slice, substr and substring JavaScript can extract a portion of a string depending on the position we specify. Even though these 3 are similar, there is a significant difference in the way the start index and end index are used.

Substring can only deal with positive values and zero. It always converts negative values to zero. Moreover, it will swap values of the start index and end index if the start index value is higher than the end index value. JavaScript substring lastindexof is an important consideration here.

As for substr, it is again index based when it comes to the starting position. The length of the characters to extract is what we pass as the second parameter value. When we pass a negative length, it will start converting characters from the end of the string.

As for slice, it is quite similar to the JavaScript substring function. The only difference is that it accepts negative numbers as in the case of substr.

In conclusion, all 3 methods are helpful if you wish to extract a portion of a string. However, you need to know the positions of the value.