JavaScript Strings

Aug 04, 2019

Lets  focus on working with strings, the JavaScript String object, and the String object’s built-in functions. You will learn how to access, compare, decompose, and search strings for commonly used real-life purposes.

JavaScript String Primitive

JavaScript’s native String primitive comes with various common string functions.

String Access

For accessing characters, you use .chartAt().

 'dog'.charAt(1); // returns "o"

.charAt(index) takes an index (which starts at 0) and returns the character at that index location in the string.

For string (multiple-character) access, you can use .substring(startIndex, endIndex), which will return the characters between the specified indices.

 'YouTube'.substring(1,2); // returns 'o' 
 'YouTube'.substring(3,7); // returns 'tube'

If you do not pass a second parameter (endIndex), it will return all the character values from the specified start position until the end.

 return 'YouTube'.substring(1); // returns 'outube'

String Comparison

Most programming languages have a function that allows you to compare strings. In JavaScript, this can be done simply by using less-than and greater-than operators.

  var a = 'a'; 
  var b = 'b'; 
  console.log(a < b); // prints 'true'

This can be really useful for comparing strings when sorting algorithms

However, if you are comparing two strings of different lengths, it starts comparing from the start of the string until the length of the smaller string.

 var a = 'add'; 
 var b = 'b'; 
 console.log(a < b); // prints 'true'

In this example, a and b are compared. Since a is smaller than b, a < b evaluates to true.

var a = 'add'; 
var b = 'ab'; 
console.log(a < b); // prints 'false'

In this example, after 'a' and 'b' are compared, 'd' and 'b' are compared. Processing cannot continue because everything in 'ab' has been looked at. This is the same as comparing 'ad' with 'ab'.

 console.log('add'<'ab' == 'ad'<'ab'); // prints 'true'
 

To find a specific string within a string, you can use .indexOf(searchValue[, fromIndex]). This takes a parameter that is the string to be searched as well as an optional parameter for the starting index for the search. It returns the position of the matching string, but if nothing is found, then -1 is returned. Note that this function is case sensitive.

 'Red Dragon'.indexOf('Red');    // returns 0 
 'Red Dragon'.indexOf('RedScale'); // returns -1 
 'Red Dragon'.indexOf('Dragon', 0); // returns 4 
 'Red Dragon'.indexOf('Dragon', 4); // returns 4 
 'Red Dragon'.indexOf(", 9);    // returns 9

To check for the occurrence of a search string inside a larger string, simply check whether -1 was returned from .indexOf.

 function existsInString (stringValue, search) { 
    return stringValue.indexOf(search) !== -1; 
 } 
   console.log(existsInString('red','r')); // prints 'true';   console.log(existsInString('red','b')); // prints 'false';

You can use an additional parameter to search after a certain index in a string. An example is counting occurrences of certain letters . In the following example, the occurrences of the character 'a' will be counted:

 var str  = "He's my king from this day until his last day"; 
 var count       = 0; 
 var pos         = str.indexOf('a'); 
 while (pos !== -1) { 
 count++; 
 pos = str.indexOf('a', pos + 1); 
 } 
 console.log(count); // prints '3'

Finally, startsWith returns true (boolean) if the string starts with the specified input, and endsWith checks whether the string ends with the specified input.

 'Red Dragon'.startsWith('Red'); // returns true 
 'Red Dragon'.endsWith('Dragon'); // returns true 
 'Red Dragon'.startsWith('Dragon'); // returns false 
 'Red Dragon'.endsWith('Red'); // returns false

String Decomposition

For decomposing a string into parts, you can use .split(separator), which is a great utility function. It takes one parameter (the separator) and creates an array of substrings.

var test1 = 'chicken,noodle,soup,broth'; 
test1.split(","); // ["chicken", "noodle", "soup", "broth"]

Passing an empty separator will create an array of all the characters.

 var test1 = 'chicken'; 
 test1.split(""); // ["c", "h", "i", "c", "k", "e", "n"]

This is useful for when there are items listed in a string. The string can be turned into an array to easily iterate through them.

String Replace

.replace(string, replaceString) replaces a specified string within a string variable with another string.

"Wizard of Oz".replace("Wizard","Witch"); // "Witch of Oz"

Neeraj Dana

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Angular, React, React-Native, Vue js, Machine Learning