You are here:   HomeJava ScriptJavascript StringJavaScript SubString
by Dinesh Thakur Category: Javascript String

That’s right; there are three methods for getting part of a string out of a larger string. First, you can use slice. It takes two parameters: the first parameter is the starting index, and the second one is the ending index, meaning the index of the character after the last character in the desired substring. If you leave the second one off, it will slice until the end of the string.

 

Example

 

var  greeting  =  "Hello,  Enotes,  what's  up?",
name  =  greeting.slice(7,  13);

alert(name);  //  Enotes

 

These index parameters can also be negative numbers, which means they  “count” from the end of the string. This way, -1 is the last item in the string, -2 is the second last, and so on.

An alternative to slice is substr. The first parameter is the same as slice the starting index but the second parameter is the length of the substring:

Example

 

var  greeting  =  "Hello,  Enotes,  what's  up?",
name  =  greeting.substr(7,  6);

alert(name);  //  Enotes

 

Since you’re string can’t have a negative length, you can’t use a negative number for the second parameter (you can use a negative number for the first parameter, though). Of course, that second parameter is optional, if you want the rest of the string.

Finally, there’s substring. This works similarly to slice, except when it comes to negative values. A negative value for either parameter acts as 0 it refers to the start of the string. The neat thing about substring is that, unlike slice, the second parameter can be lower than the first (while still positive). When this is the case, substring goes back to the character of that index. For example,

Example

 

var  greeting  =  "Hello,  Enotes,  what's  up?",
name  =  greeting.substring(13,  7);

alert(name);  //  Enotes

 



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.



What's New and Popular





Search Content







Advance Courses



Basic Courses



Advertise with Us