The Complete JavaScript Strings Reference

Ciprian on Tuesday, August 9, 2022 in JavaScript Arrays & Objects, Methods, Events and Scopes

NEW! Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

JavaScript strings are deceptively complex constructs. There are actually two different types of strings – string Literals and string Objects – and they both behave somewhat differently, even while trying to masquerade as the other. Strings, in addition to having some pretty funky methods of dubious usefulness, have a great many oversights and shortcomings which can be smoothed over with a few prototypes.

This reference will cover the difference between String Literals and String Objects, Strings’ properties and methods, some common and practical uses of Strings (particularly in regard to JSON and AJAX), and offer a few, useful prototypes to extend the String class.

Table of Contents

Literal or Object?

There are two different types of Strings, and they behave quite differently. A Literal is created just by using quotes around your string. An object is created by implicit use of the new keyword. If you assign a string to a variable using the String keyword, without the new keyword, the contents of the parenthesis will be cast as a string Literal.

var StringLiteral = "This is a string Literal";
    StringObject  = new String("This is a string object");
    StringTest    = String(12345.68);
    
console.log(typeof(StringLiteral) + '<br>'); // Outputs: string
console.log(typeof(StringObject) + '<br>');  // Outputs: object
console.log(typeof(StringTest) + '<br>');    // Outputs: string

A string literal has access to all of a string’s objects and methods because JavaScript will temporarily cast a string literal as a string object in order to run the desired method.

var StringLiteral = "This is a string Literal";
    StringObject  = new String("This is a string object");

StringLiteral = StringLiteral.concat('!!!');
StringObject  = StringObject.concat('###');
    
console.log(StringLiteral + '<br>');  // Outputs: This is a string Literal!!!
console.log(StringObject + '<br>');   // Outputs: This is a string object###

Where the two differ is their treatment of new properties and methods. Like all JavaScript objects, you can assign properties and methods to any String object.

var alpha = new String("This is the first String Object");
var beta  = new String("This is a second String Object");
var delta = "This is a String Literal";

alpha.property1 = 'This is private to alpha';
alpha.display = function () {
   console.log('String: ' + this + '<br>');
   console.log('Property: ' + this.property1 + '<br>');
}

alpha.display();
   // Outputs:
   // String: This is the first String Object
   // Property: This is private to alpha
beta.display();
   // Generates an error since we never gave beta any
   // properties or methods.
delta.display();
   // Generates an error since we never gave the String
   // prototype any properties or methods.

You can not add properties or methods to a string literal. They are ignored by the interpreter.

var alpha = "This is a string literal!";

alpha.property1 = 10;
alpha.method1 = function() { console.log('hello world!'); }

console.log(alpha.property1 + '<br>'); // outputs: undefined
alpha.method1(); // Generates an error.

The reason you can’t add properties or methods to a string literal is that when you try to access a literal’s property or method, the JavaScript interpreter temporarily copies the value of the string into a new object and then use that object’s properties or methods. This means a String literal can only access a string’s default properties or methods and those that have been added as prototypes.

var alpha = new String("This is the first String Object");
var beta  = new String("This is a second String Object");
var delta = "This is a String Literal";

String.prototype.property1 = 'This is public to all Strings Objects Or Literals';
String.prototype.display = function () {
   console.log('String: ' + this + '<br>');
   console.log('Property: ' + this.property1 + '<br>');
}

alpha.display();
   // Outputs:
   // String: This is the first String Object
   // Property: This is public to all Strings Objects Or Literals
beta.display();
   // Outputs:
   // String: This is the second String Object
   // Property: This is public to all Strings Objects Or Literals
delta.display();
   // Outputs:
   // String: "This is a String Literal"
   // Property: This is public to all Strings Objects Or Literals

A final caveat is that literals and objects are treated differently by the eval statement.

var alpha = "2 + 2";              // alpha is a string literal
var beta = new String("2 + 2");   // beta is a string object
console.log(eval(alpha) + '<br>');          // Outputs: 4
console.log(eval(beta) + '<br>');           // Outputs: 2+2
console.log(eval(beta.valueOf()) + '<br>'); // Outputs: 4

Strings Are Passed To Functions As Values

Unlike true objects and arrays, all strings (Literal or Objects) are passed to functions as values, which means anything you do to the string inside the function does not affect the original value.

var alpha = "This is a string literal";
    beta = new String("This is a string object");
    
function changeString(strlit, strobj) {
   var strlit = 'changed!!!';
   var strobj = 'changed!!!';
}

changeString(alpha, beta);

console.log(alpha + '<br>'); // Outputs: This is a string literal
console.log(beta + '<br>');  // Outputs: This is a string object

Casting a String

You can cast data as a String through the use of the String command. When used in this way, the String returns the content’s valueOf result, which is always a string. Additionally, you can use the plus sign to append a null string to the object, thus casting it as a string.

var numString  = String(1234.36);
var numArray   = String([1,2,3,4,5]);
var numObject  = String({'color':'blue', 'song' : 'sung'});
var numString2 = 1234.36 + '';

console.log(typeof(numString) + ' - ' + numString + '<br>');
console.log(typeof(numArray) + ' - ' + numArray + '<br>');
console.log(typeof(numObject) + ' - ' + numObject + '<br>');
console.log(typeof(numString2) + ' - ' + numString2 + '<br>');

// outputs:
// string - 1234.36
// string - 1,2,3,4,5
// string - [object Object]
// string - 1234.36

As you can see, casting an Object as a String returns an unexpected result.

var numObject = String({'color':'blue', 'song' : 'sung'}.toSource());

console.log(typeof(numObject) + ' - ' + numObject + '<br>');

//outputs:
//({color:"blue", song:"sung"})

String Properties

All strings have a length property which return the length of the string.

   alpha = "abcdefghijklmnopqrstuvwxyz";
   beta  = new String("abcdefghijklmnopqrstuvwxyz");
   
   console.log(alpha.length + '<br>');  // Outputs: 26
   console.log(beta.length + '<br>');   // Outputs: 26

String Method Reference

General Methods

The following methods are a part of the String object and are available to String literals as well. As you move the mouse over each row, it will be highlighted to make it easier to read the table. If you click on a method, you will be taken to that method’s detailed instructions.

MethodNotes
charAtReturns the character at index.
charCodeAtReturns the Unicode Value.
concatJoins Strings
fromCharCodeCreates a string from the supplied unicode integers.
indexOfFinds position of a substring.
lastIndexOfFinds position of a substring.
localeCompareCompares two strings.
replaceReplaces a substring within a string.
sliceExtracts a substring starting at the index.
splitReturns an array with the delimiter as the pivot.
substrExtracts x characters of a String starting at Index
substringExtracts a substring from index to ending Index
toLocaleLowerCaseConverts a language-localized string to lower case
toLocaleUpperCaseConverts a language-localized string to upper case
toLowerCaseConverts the string to lower case
toStringReturns the String Object as a String
toStringReturns the String Object as a String
toUpperCaseConverts the string to upper case
valueOfSee toString()

String Method Reference (Regular Expressions)

These methods use regular expressions to do search and replace on strings. In general, methods exist above which allow you to do without regular expression methods, however if you’re familiar with regular expressions you’ll find these methods to be quick and easy (and in some cases, a whole new can of worms/bugs). These methods are available to all Strings, be they Objects or Literals.

MethodNotes
matchDoes a pattern search on a string.
replaceReplaces a substring within a string.
searchSearches for a pattern within a string.

String Method Reference (HTML wrappers)

These methods aren’t very useful since only a trivial few HTML tags are supported. It’s like someone started doing these then decided they were silly (which, for the most part, they are) and stopped, but left what they had already done in interpreter where they became a part of the language. These methods are available to all Strings, whether Objects or Literals.

MethodNotes
anchorCreates an Anchor Tag for the string.
bigWraps the string in HTML <big> tags.
blinkWraps the string in HTML <blink> tags.
boldWraps the string in HTML <b> tags.
fixedWraps the string in HTML <tt> tags.
fontcolorWraps the string in HTML <font color='{color}’> tags.
fontsizeWraps the string in HTML <font size='{size}’> tags.
italicsWraps the string in HTML <i> tags.
linkCreates a hypertext link from the string.
smallWraps the string in HTML <small> tags.
strikeWraps the string in HTML <strike> tags.
subWraps the string in HTML <sub> tags.
supWraps the string in HTML <sup> tags.

String.anchor(nameAttribute)

This method creates an anchor attribute for the string. You supply an index value and the method will return an HTML string, leaving the original string untouched.

var myString = "Table of Contents";
var htmlString = myString.anchor("TOC"); 

// htmlString = <A NAME="TOC">Table of Contents</A>

String.big()

This method wraps the string in the HTML big tag (Big Text).

var myString = "Table of Contents";
var htmlString = myString.big(); 

// htmlString = <big>Table of Contents</big>

String.bold()

This method wraps the string in the HTML <b> (bold) tag.

var myString = "Table of Contents";
var htmlString=myString.bold(); 

// htmlString = <b>Table of Contents</b>

String.charAt(Index)

This method returns the character at a specific index starting with zero. If a string has a length of 26 then charAt‘s range is 0-25. If you ask for a value which is out of range (the 53rd position of a string that’s only 26 characters long, for instance) this method will return an empty string (”), which is NOT the same as null. (test for an empty string, not null).

   alpha = "abcdefghijklmnopqrstuvwxyz";
   beta = new String("abcdefghijklmnopqrstuvwxyz");
   
   console.log(alpha.charAt(3)+'<br>');  // Outputs: d
   console.log(beta.charAt(3)+'<br>');   // Outputs: d
   console.log(alpha[3]+'<br>');         // Outputs: d, undefined in IE
   console.log(beta[3]+'<br>');          // Outputs: d, undefined in IE

   // Position out of range return an empty string.
   console.log(alpha.charAt(53)+'<br>'); // Outputs: ''
   console.log(beta.charAt(53)+'<br>');  // Outputs: ''

String.charCodeAt(Index)

This method returns the Unicode value of the character at the requested index. This method works the same as charAt() but instead of a character it returns a number representing the Unicode value of the character. In very ancient versions of JavaScript, this number represented the ISO-Latin-1 character set rather than Unicode, however, the percentage of these browsers still in use today are so small it’s considered safe to assume a Unicode result. If you request an index which doesn’t exist, JavaScript returns NaN (Not a Number, which is a JavaScript reserved word/value in the same vein as null and undefined).

   alpha = "abcdefghijklmnopqrstuvwxyz";
   beta = new String("abcdefghijklmnopqrstuvwxyz");
   
   console.log(alpha.charAt(3)+'<br>');  // Outputs: 100
   console.log(beta.charAt(3)+'<br>');   // Outputs: 100

   // Position out of range return an empty string.
   console.log(alpha.charAt(53)+'<br>'); // Outputs: NaN
   console.log(beta.charAt(53)+'<br>');  // Outputs: Nan

String.concat(String[, String[, String…]])

The concat method joins the supplied strings to the original, returning a new string as a result. You can also use the plus sign (+) to achieve the same effect. There is no difference between string Objects and String Literals in the following example.

var alpha = " String 1 ";
var beta = " String 2 ";
var delta = " String 3 ";

newString1 = alpha + beta + delta;
newString2 = alpha.concat(beta, delta);
alpha += beta + delta;
   
console.log(newString1+'<br>'); // outputs:  String 1 String 2 String 3 
console.log(newString2+'<br>'); // outputs:  String 1 String 2 String 3 
console.log(alpha+'<br>');      // outputs:  String 1 String 2 String 3 

Numbers will be cast as strings for the concatenation. When using + to join strings, ANY string in the equation will do a string concatenation on all the items which follow. That’s a bit confusing but say we have 5+20+42+"string", then the result will become 67 String, so we did straight addition up to the string. AFTER the string, every addition becomes a string concatenation, so 5+20+42+" string "+20+5 becomes 67 String 205. The second part of the equation becomes string concatenation, so 20 is appended with 5 instead of having 5 added to 20.

var alpha = "35";
var   beta = 60;

newString1 = alpha + beta;
newString2 = alpha.concat(beta);
alpha += beta;
delta = 5+20+42+" String "+10+5;
   
console.log(newString1+'<br>'); // Outputs 3560
console.log(newString2+'<br>'); // Outputs 3560
console.log(alpha+'<br>');      // Outputs 3560
console.log(delta+'<br>');      // Outputs 67 String 105

String.fixed()

This method wraps the string in the HTML tt tag (fixed-pitch font).

var myString = "Table of Contents";
var htmlString=myString.fixed();

// htmlString = <tt>Table of Contents</tt>

String.fromCharCode(code1[, code#…])

This method accepts a series of Unicode characters and converts them to a JavaScript string. This method is a bit unusual in that it’s really more of a function than a String method, since it doesn’t act on the data contained in the string. Because of this, you don’t need to use a string to access this method, you can simply use the String object itself.

var test = String.fromCharCode(112, 108, 97, 105, 110);
console.log(test); // outputs: plain

String.indexOf(SearchValue[, startIndex])

IndexOf returns an index where the passed SearchValue was found, or -1 if the search value was not found. You can also supply an optional starting index (StartIndex) where the method will start its search.

var alpha = 'The brown fox was faster than the white fox.';
var beta  = new String('The brown fox was faster than the white fox.');

console.log(alpha.indexOf('fox')+'<br>'); // Outputs 10;  
console.log(beta.indexOf('fox')+'<br>');  // Outputs 10;

// Now we'll start looking after the first position and get the second.
console.log(alpha.indexOf('fox',11)+'<br>'); // Outputs 40;  
console.log(beta.indexOf('fox',11)+'<br>');  // Outputs 40;

// Look for something which isn't there.
console.log(beta.indexOf('bear')+'<br>');    // Outputs -1;

String.italics()

This method wraps the string in the HTML <i> tag (italics).

var myString = "Table of Contents";
var htmlString=myString.italics();

// htmlString = <i>Table of Contents</i>

String.lastIndexOf(SearchValue[, startIndex])

This method is the same as the indexOf method, however it searches from the end of the string to the beginning of the string.

var alpha = 'The brown fox was faster than the white fox.';
var beta  = new String('The brown fox was faster than the white fox.');

console.log(alpha.lastIndexOf('fox')+'<br>'); // Outputs 40;  
console.log(beta.lastIndexOf('fox')+'<br>');  // Outputs 40;

// Now we'll start looking after the first position and get the second.
console.log(alpha.lastIndexOf('fox',39)+'<br>'); // Outputs 10;  
console.log(beta.lastIndexOf('fox',39)+'<br>');  // Outputs 10;

// Look for something which isn't there.
console.log(beta.lastIndexOf('bear')+'<br>');    // Outputs -1;

String.link(url)

This method creates a hypertext link for the string. You supply a URL as the first argument and the method will return an HTML string, leaving the original string untouched.

var myString = "Table of Contents";
var htmlString = myString.link("https://getbutterfly.com/"); 

// htmlString = <a href="https://getbutterfly.com/">Table of Contents</a>

String.match(regExp)

The match method uses a regular expression to determine if a substring exists within the string. If the substring exists, it will return the substring. If you looked for multiple occurrences (/string/g) and more than one result is found, it will return an array containing all the matches. Match takes 2x (best-case) as long to execute as IndexOf.

str = 'Now is the time for all good men to come to the aid of their country!';

result = str.match(/the/ig);  // Look for "the" case insensitive (i), all occurrences (g)
console.log(result+'<br>'); // Outputs array: the, the, the

result = str.match(/^now/i); // Look for "now", case insensitive(i), start of string (^)
console.log(result+'<br>'); // Outputs array: Now

// Here we look for something that's not there -- "the" as the start of the string
// the result is null which means result will evaluate to false if we do...
// if not(result) { alert('we found nothing!'); }

result = str.match(/^the/i); // Look for "the" case insensitive(i), start of string (^)
console.log(result+'<br>'); // Outputs array: null

// The next example does pattern matching which, in this case, means we're looking for
// something that looks like a telephone number.

str = "Jenny's Number is 867-5309.  At least back in the 80's";

result = str.match(/\d{3}-\d{4}/); // Search for 3 digits, dash, 4 digits
console.log(result+'<br>');   // Outputs: 867-5309 

String.replace(regExp/substr, replacementValue[, flags])

This is one of String’s more complex methods, and correspondingly, one of the most powerful. At its simplest, this method will look for the supplied substring and, if found, replace it with the supplied replacement string. The result of the replacement is returned as a new string. The original string remains untouched.

str = "Jenny's Number is 867-5309.  At least back in the 80's. The 80's were cool.";
result = str.replace("Jenny's", "Bob's");  // Replace Jenny's With Bob's

console.log(result); 
// outputs: 
//Bob's Number is 867-5309.  At least back in the 80's. The 80's were cool.

This example works on a direct match. If we forgot to capitalize the J in Jenny, the replace would fail.

str = "Jenny's Number is 867-5309.  At least back in the 80's. The 80's were cool.";
result = str.replace("jenny's", "Bob's");  // Replace jenny's With Bob's

console.log(result); 
// outputs: 
//Jenny's Number is 867-5309. At least back in the 80's. The 80's were cool.

If we would like to ignore the case of the original string, we can specify an optional flag. The flags are:

  • g — global, match more than one occurrence.
  • i — case-insensitive
  • m — match over multiple lines (useful for <pre> text)

Here we’ll supply an i flag, so the previous example will work.

str = "Jenny's Number is 867-5309.  At least back in the 80's. The 80's were cool.";
result = str.replace("jenny's", "Bob's", "i");  // Replace J/jenny's With Bob's

console.log(result); 
// outputs: 
//Bob's Number is 867-5309.  At least back in the 80's. The 80's were cool.

If you would like to use the flags outside of Firefox, you’ll need to convert the search string to a regular expression. This is actually pretty easy. Instead of using quotes, use forward slashes, and at the end of the expression simply append the flags you would like the flag to use. In our above example…

result = str.replace("jenny's", "Bob's", "i");  // Replace J/jenny's With Bob's

…becomes…

result = str.replace(/jenny's/i, "Bob's");      // Replace J/jenny's With Bob's

In this next example, we’ll replace the with ***. Note that only the first occurrence will be replaced in the first example, but in the second, since we added a g flag (in addition to i) both occurrences of the will be replaced.

str = "Jenny's Number is 867-5309.  At least back in the 80's. The 80's were cool.";
result = str.replace(/the/i, "***");  // Replace "the" with "***", case insensitive

console.log(result); 
// outputs: 
//Jenny's Number is 867-5309.  At least back in *** 80's. The 80's were cool.

str = "Jenny's Number is 867-5309.  At least back in the 80's. The 80's were cool.";
result = str.replace(/the/ig, "***");  // Replace "the" with "***", case insensitive

console.log(result); 
// outputs: 
//Jenny's Number is 867-5309.  At least back in *** 80's. *** 80's were cool.

If you opt to use a regular expression, then you need to specify your flags as regular expression modifiers instead of passing them as arguments.

A more powerful and practical example of a regular expression replace looks for something resembling a telephone number and masks it out with # signs. The following example matches all 3 digit, dash, 4 digit patterns and replaces it with ###-####.

str = "Jenny's Number is 867-5309.  At least back in the 80's. The 80's were cool.";
result=str.replace(/[\d{3}\-\d{4}]+/,'###-####','g');
console.log(result);
// outputs:
// Jenny's Number is ###-####. At least back in the 80's. The 80's were cool.

You can use a function as the replacement value. The replace method will use the return value of your function as the replacement value. It is unfortunate, but the arguments passed to your function are not well-thought-out. If you used strings as your search criteria instead of regular expressions, then the parameters will always be…

function myReplace(matchedSubstring, Index, OriginalString)

matchedSubstring will be the substring which was found and is going to be replaced. Index was the numerical position the substring was found inside the string. OriginalString is the full string that was searched. If you specified a g flag, then your function will be called each time a match was found.

The unfortunate part referred to earlier is that if you used a regular expression then parenthetical matches will be inserted between the matchedSubstring and the Index, so there’s no constant you can use to refer to the Index or OriginalString save by using the argument’s array, which needlessly increases the complexity of the function.

Here, we’ll replace all numbers with either a (if less than or equal to 5) or b (if greater than 5). We’re using a regular expression as our search String, however since we’re not using parenthetical matches our function arguments will be constant.

function checkit(matchedSubstring, Index, OriginalString) {
   if (matchedSubstring<=5) { return 'a' } else {return 'b'}
}

str = "Jenny's Number is 867-5309.  At least back in the 80's. The 80's were cool.";
result=str.replace(/\d/g, checkit); // Search for any digits, call checkit for replacement

console.log(result);
// outputs: 
//Jenny's Number is bbb-aaab. At least back in the ba's. The ba's were cool.

Finally, there are some special codes you can use in your replacement string:

  • $$ — Inserts a dollar sign.
  • $& — Inserts the matched substring
  • $` — Inserts the portion of the string which preceded the match.
  • $' — Inserts the portion of the string which followed the match.
  • $n — Inserts the Nth parenthesized substring match (assuming the first argument was a regular expression and not a substring)

The following example takes all number groups and wraps them in brackets using the $& replacement string.

str = "Jenny's Number is 867-5309.  At least back in the 80's. The 80's were cool.";
result=str.replace(/(\d+)/g,'[$&]','g');
console.log(result);

// Outputs:
//Jenny's Number is [867-5309].  At least back in the [80]'s. The [80]'s were cool.

String.search(regExp)

This method accepts a regular expression as an argument and returns the index in the string where the pattern was matched, or -1 if the pattern could not be matched. If more than one occurrence of the pattern exists, only the first index will be returned.

This method is similar to indexOf except that it’s twice as slow and doesn’t allow more than one item to be matched. So if possible, you should stick with indexOf.

str = "Once upon a time the big, bad ogre ate the goat, the mistral sang";
result=str.search(/(the)+/ig);
console.log(result);           // outputs: 17

String.slice(startIndex[, endIndex])

Slice will extract a substring starting at the specified starting index and ending at the specified ending index. If endIndex is less than or equal to startIndex, the slice method will return a null string. If endIndex is not specified the slice Method will extract to the end of the string.

The original string is untouched.

str = "Jenny's Number is 867-5309.";

result = str.slice(8,14);  // Contains: Number
result = str.slice(8);     // Contains: Number is 867-5309.
result = str.slice(8,3);   // Null
result = str.slice(100);   // Null

String.small()

This method wraps the string in the HTML <small> (Small Text)tag.

var myString = "Table of Contents";
var htmlString=myString.small();

// htmlString = <small>Table of Contents</small>

String.split(delimiter[, limit])

This is one of the most powerful of the String methods. Given a delimiter as the first argument, split() will create an array with each element containing an item separated by the delimiter in the original string. That’s a bit wordy so lets just show you the code…

str = "One~Two~Three~Four~Five";
newArray = str.split('~');
for(i=0; i<newArray.length; i++) {
   console.log(i+'-'+newArray[i]+'<BR>');
}

// outputs: 
// 0-One
// 1-Two
// 2-Three
// 3-Four
// 4-Five

The above example has a string with 5 words separated by the tilde (~) character. The split breaks the string into an array using the tilde as the delimiter.

A very real world example is that you can use this method to receive an array from the server via Ajax. You’ll receive the array as a string with a unique delimiter, just like in our example. By running the string through the split method, we have now reconstructed our array as it appears on the server.

If you would like to manipulate a string as a true array (for speed or other reasons) then you can easily convert a string to an array and then back again. To convert each index in a string to its corresponding index in an Array just use a null string as a delimiter.

str='The quick brown fox';
newArray = str.split('');
for(i=0; i<newArray.length; i++) {
   console.log(newArray[i]+', ');
}
//outputs: 
//T, h, e, , q, u, i, c, k, , b, r, o, w, n, , f, o, x,

And to reverse the process, use the Array‘s join() method with a null string.

str=newArray.join('');
console.log(str);
//outputs:
//The quick brown fox

Using the String method, split() and the Array method, join() you can easily manipulate strings as arrays. String.split() can convert incoming AJAX data into arrays, and Array.join can convert a JavaScript array into a string ready to be sent to the server via Ajax – just use a unique delimiter in your join method instead of a null string, as such:

toServer=newArray.join('~'); // Creates a string delimitated by tildies (~)

The optional limit parameter specifies how many array elements will be made. For instance, if you have a 30,000 character string, and you only need the first 100 characters you would use:

newArray = str.split('',100);

String.strike()

This method wraps the string in the HTML <strike> (strikeout effect) tag.

var myString = "Table of Contents";
var htmlString=myString.strike();

// htmlString = <strike>Table of Contents</strike>

String.sub()

This method wraps the string in the HTML <sub> (subscript) tag.

var myString = "Table of Contents";
var htmlString=myString.sub();

// htmlString = <sub>Table of Contents</sub>

String.substr(index[, numChars])

The substr() method is similar to the slice() method, save that the second argument indicates how many characters to include instead of an ending index. If numChars is not a positive number, then substr will return an empty string. If numChars is omitted, then substr will extract a string from the index to the end of the string.

substr returns a new string. The original string is left untouched.

var str='The quick brown fox';
var speed = str.substr(4,5);  // contains: quick
var speed = str.substr(4);    // contains: quick brown fox
var speed = str.substr(4,-2); // contains: ''

String.substring(index[, stopIndex])

This method is nearly identical to the slice() method. The only real difference is that if stopIndex is less than index, instead of returning an empty string, substring() will extract the string from the stopIndex to the Index (effectively reversing the numbers for you).

result = str.substring(8,14);  // Contains: Number
result = str.substring(8);     // Contains: Number is 867-5309.
result = str.substring(8,0);   // Contains: Jenny's
result = str.substring(100);   // Null
result = str.substring(100,0); // Contains: Jenny's Number is 867-5309.

String.sup()

This method wraps the string in the HTML <sup> (superscript) tag.

var myString = "Table of Contents";
var htmlString=myString.sup();

// htmlString = <sup>Table of Contents</sup>

String.toLowerCase()

This method simply returns the string as all lower case. The original string is left untouched. (See also: toUpperCase())

var str = 'AbCdEfGhIjKlMnOpQrStUvWxYz';
var result = str.toLowerCase();

console.log(result); // Outputs: abcdefghijklmnopqrstuvwxyz 

String.toString()

This method overrides the default Object.toString() method. Your use of this method would be fairly redundant.

strObj = new String("Hello World");
strLit = "Hello World";
console.log(strObj.toString()+'<br>');         // Outputs: Hello World
console.log(typeof(strObj.toString())+'<br>'); // Outputs: string

console.log(strLit.toString()+'<br>');         // Outputs: Hello World
console.log(typeof(strLit.toString())+'<br>'); // Outputs: string

String.toUpperCase()

This method simply returns the string as all upper case. The original string is left untouched. ( See also: toLowerCase() )

var str = 'AbCdEfGhIjKlMnOpQrStUvWxYz';
var result = str.toLowerCase();

console.log(result); // Outputs: ABCDEFGHIJKLMNOPQRSTUVWXYZ 

String.valueOf()

See String.toString()

Converting Arrays To Strings For Ajax

If you need to send an array to a server through an Ajax call, you’ll need to convert the array to a string before you can do it. This is easy enough to do with the Array’s join() method. Simply pick a unique character that is unlikely to appear in your array. For this purpose, a tilde (~) is usually a safe character.

var myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
var ajaxStr = myArray.join('~'); // contains: 1~2~3~4~5~6~7~8~9~10~11~12~13~14

You can now send ajaxStr to the server, where it can be broken out into an array again.

Converting Strings into Arrays For Ajax

If you’ve received a string as an array via Ajax you’ll need to convert that string back into an array in JavaScript. This is very simple to do! Just use the string’s split() method to convert the string into the array. In this example, we’ll assume the server used the tilde (~) as the delimiter.

var ajaxStr = "1~2~3~4~5~6~7~8~9~10~11~12~13~14"; // What we got from the server.
var myArray = ajaxStr.split('~'); // Turn the string into an Array

//MyArray now contains: 1,2,3,4,5,6,7,8,9,10,11,12,13,14;

Useful Prototypes

While the String methods in JavaScript are powerful and useful, there is still room for improvement and thanks to prototyping you can add whatever useful features you want!

Useful Prototypes: trim()

Removing leading and trailing whitespace is something which should have shipped with JavaScript from the start, but it’s easy enough to make up for the designer’s oversight.

String.prototype.trim = function() {
   return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
   return this.replace(/^\s+/g,"");
}
String.prototype.rtrim = function() {
   return this.replace(/\s+$/g,"");
}

Usage:

var test = "   Test   ";
var test1 = test.ltrim();   // returns "Test   "
var test2 = test.rtrim();   // returns "   Test"
var test3 = test.trim();    // returns "Test"

Useful Prototypes: htmlEntities()

This method escapes all &, <, and > symbols in the string, making it safe to display the string on a web page without fear that it will be treated as HTML.

String.prototype.htmlEntities = function () {
   return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
};

Usage:

var tmp = '<html><head></head>';
var safe= tmp.htmlEntities(); // Returns &lt;html&gt;&lt;head&gt;&lt;/head&gt;

Useful Prototypes: stripTags()

This method will remove all < > tags (and everything in between), ensuring that the string contains no HTML.

String.prototype.stripTags = function () {
   return this.replace(/<([^>]+)>/g,'');
}

Usage:

var tmp = '<a href="http://somespammer.com">Some Link</a>';
var safe= tmp.stripTags(); // Returns: Some Link;

Useful Prototypes: toArray()

This method explodes the string out into an array of characters.

String.prototype.toArray = function() {
   return this.split('');
}

Usage:

var str='AbCdEfGhIjKlMnOpQrStUvWxYz';
var arr=str.toArray();

for (var i=0; i<arr.length; i++) {
   console.log(arr[i]+', ');
}
//Outputs:
//A, b, C, d, E, f, G, h, I, j, K, l, M, n, O, p, Q, r, S, t, U, v, W, x, Y, z,

Useful Prototypes: toIntArray()

This method explodes the string out into an array of integers representing the character’s Unicode.

String.prototype.toIntArray = function() {
   var returnArray = [];
   for (var i=0; i<this.length; i++) {
      returnArray.push(this.charCodeAt(i));
   }
   return returnArray;
}

Usage:

var str='AbCdEfGhIjKlMnOpQrStUvWxYz';
var arr=str.toIntArray();

for (var i=0; i<arr.length; i++) {
   console.log(arr[i]+', ');
}
// Outputs:
// 65, 98, 67, 100, 69, 102, 71, 104, 73, 106, 75, 108, 77, 
// 110, 79, 112, 81, 114, 83, 116, 85, 118, 87, 120, 89, 122,

Related posts

Leave a Reply