Categories
JavaScript Tutorials

The String Object

Using the String() constructor function you can create string objects. Objects produced this way provide some useful methods when it comes to text manipulation, but if you don’t plan on using these methods, you’re probably better off just using primitive strings.

Here’s an example that shows the difference between a string object and a primitive string data type.

var primitive = 'Hello';
typeof primitive;
//"string"
var obj = new String('world');
typeof obj;
//"object"

A string object is very similar to an array of characters. The string objects have an indexed property for each character and they also have a length property.

obj[0]
//"w"
obj[4]
//"d"
obj.length
//5

To extract the primitive value from the string object, you can use the valueOf() or toString() methods inherited from Object. You’ll probably never need to do this, as toString() is called behind the scenes if you use an object in a string context.

obj.valueOf()
//"world"
obj.toString()
//"world"
obj + ""
//"world"

Primitive strings are not objects, so they don’t have any methods or properties. But JavaScript still offers you the syntax to treat primitive strings as objects.In the following example, string objects are being created (and then destroyed) behind the scenes every time you access a primitive string as if it was an object:

"potato".length
//6
"tomato"[0]
//"t"
"potato"["potato".length - 1]
//"o"

One final example to illustrate the difference between a string primitive and a string object: let’s convert them to boolean. The empty string is a falsy value, but any string object is truthy.

Boolean("")
//false
Boolean(new String(""))
//true

Similarly to Number() and Boolean(), if you use the String() function without new, it converts the parameter to a primitive string. This means calling toString() method, if the input is an object.

String(1)
//"1"
String({p: 1})
//"[object Object]"
String([1,2,3])
//"1,2,3"

Interesting Methods of the String Objects

Let’s experiment with some of the methods you can call for string objects. Start off by creating a string object:

var s = new String("Couch potato");

toUpperCase() and toLowerCase() are convenient ways to transform the capitalization of the string:

s.toUpperCase()
//"COUCH POTATO"
s.toLowerCase()
//"couch potato"

charAt() tells you the character found at the position you specify, which is the same as using square brackets (a string is an array of characters).

s.charAt(0);
//"C"
s[0]
//"C"

If you pass a non-existing position to charAt(), you get an empty string:

s.charAt(101)
//""

indexOf() allows you to search within a string. If there is a match, the method returns the position at which the first match is found. The position count starts at 0, so the second character in “Couch” is “o” at position 1.

s.indexOf('o')
//1

You can optionally specify where (at what position) to start the search. The following finds the second “o”, because indexOf() is instructed to start the search at position 2:

s.indexOf('o', 2)
//7

lastIndexOf() starts the search from the end of the string (but the position of the match is still counted from the beginning):

s.lastIndexOf('o')
//11

You can search for strings, not only characters, and the search is case sensitive:

s.indexOf('Couch')
//0

If there is no match, the function returns a position -1:

s.indexOf('couch')
//-1

To perform a case-insensitive search you can transform the string to lowercase first and then search it:

s.toLowerCase().indexOf('couch')
//0

When you get 0, this means that the matching part of the string starts at position 0. This can cause confusion when you check with if, because if will convert the position 0 to a boolean false. So while this is syntactically correct, it is logically wrong:

if (s.indexOf('Couch')) {...}

The proper way to check if a string contains another string is to compare the result of indexOf() to the number -1.

if (s.indexOf('Couch') !== -1) {...}

slice() and substring() return a piece of the string when you specify start and end positions:

s.slice(1, 5)
//"ouch"
s.substring(1, 5)
//"ouch"

Note that the second parameter you pass is the end position, not the length of the piece. The difference between these two methods is how they treat negative arguments. substring() treats them as zeros, while slice() adds them to the length of the string. So if you pass parameters (1, -1) it’s the same as substring(1, 0) and slice(1, s.length – 1):

s.slice(1, -1)
//"ouch potat"
s.substring(1, -1)
//"C"

The split() method creates an array from the string, using a string that you pass as a separator:

s.split(" ")
//["Couch", "potato"]

split() is the opposite of join() which creates a string from an array:

s.split(' ').join(' ');
//"Couch potato"

concat() glues strings together, the way the + operator does for primitive strings:

s.concat("es")
//"Couch potatoes"

Note that while some of the methods discussed above return new primitive strings, none of them modify the source string. After all the methods we called, our initial string is still the same:

s.valueOf()
//"Couch potato"

We looked at indexOf() and lastIndexOf() to search within strings, but there are more powerful methods (search(), match(), and replace()) which take regular expressions as parameters. You’ll see these later, when we get to the RegExp() constructor function.

Examples

Create a string and print the number of characters in the string.

<script>
  var str = 'hello';
  console.log(str.length);
</script>

Create a string and change the text to uppercase.

var str = 'hello';
str.toUpperCase();

Create a string and change the text to lowercase.

var str = 'hello';
str.toLowerCase();

Create a string and print the last character.

var str = 'hello';
console.log(str[str.length-1]);

Create a string and check whether a given character is present in the string or not.

<script>
  var check = prompt('Enter a character');
  var str = 'hello';
  if(str.indexOf(check)===-1){
    console.log('The given character is not present');
  }
  else{
    console.log('The given character is present');
  }

Create a six letter string and extract the first four characters of the string.

<script>
  var str = 'cancel';
  var piece = str.slice(0,4);
  console.log(piece);
</script>