Extract Part of a String
By Stephen Bucaro
Use the String object's .slice method to extract part of a string. The syntax
for the .slice method is shown below.
string.slice(start,end)
Where start is the character location to begin the extraction, the first character
in a string being position 0, and end being the location to end the extraction,
everything up to, but not including, the character at the end location being included
in the returned substring.
In the example below, the .slice method is used to extract the document name
part of a URL string, not including the file extension.
<script>
var urlStr = "domain.ext/directory/filename.ext";
var docStr = urlStr.slice(21,29);
alert(docStr);
</script>
The end parameter is optional in the .slice method. If the end
parameter is not included, all the characters to the end of the string are extracted.
In the example below, the .slice method is used to extract the document name
part of a URL string, including the file extension.
<script>
var urlStr = "domain.ext/directory/filename.ext";
var docStr = urlStr.slice(21);
alert(docStr);
</script>
To extract part of the end of a string, use a negative number equal to the number of
characters you want to extract. In the example below, the .slice method is
used with a negative number to extract only file extension, not including the dot.
<script>
var urlStr = "domain.ext/directory/filename.ext";
var docStr = urlStr.slice(-3);
alert(docStr);
</script>
One problem with the String object's .slice method is that you have to know
beforehand the location of the substring that you want to extract. Lets assume from
the previous examples that I didn't know the location of the filename in the URL.
In the example below I use the String object's .lastIndexOf method to locate
the last slash and last dot characters in the URL string, then I use that information
in the .slice method to extract the filename, not including the file extension.
<script>
var urlStr = "domain.ext/directory/filename.ext";
var loc1 = urlStr.lastIndexOf("/");
var loc2 = urlStr.lastIndexOf(".");
var docStr = urlStr.slice(loc1+1,loc2);
alert(docStr);
</script>
More Java Script Code: • The do/while Loop • Java Script Quick Reference : JavaScript toString Method Converts a Number to a String • The Browsers History Object • Get Webpage File Date and File Size • Java Script Math.cos Method • Comparison Operators • Java Script Math.sin Method • Use moveBy Method to Move Window by a Specific Offset • Determine Minimum and Maximum • The Screen Object
|