Pages

Friday, June 18, 2021

JavaScript Strings

 JavaScript strings are used for storing and manipulating text. A JavaScript string is zero or more characters written inside quotes.

Example

var x = "John Doe";

You can use single or double quotes:

Example

var carName1 = "Volvo XC60";  // Double quotes
var carName2 = 'Volvo XC60';  // Single quotes

You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

Example

var answer1 = "It's alright";
var answer2 = "He is called 'Johnny'";
var answer3 = 'He is called "Johnny"';


String Length

To find the length of a string, use the built-in length property:

Example

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;

Escape Character

Because strings must be written within quotes, JavaScript will misunderstand this string:

var x = "We are the so-called "Vikings" from the north.";

The string will be chopped to "We are the so-called ".

The solution to avoid this problem, is to use the backslash escape character.

The backslash (\) escape character turns special characters into string characters:

Code

Result

Description

\'

'

Single quote

\"

"

Double quote

\\

\

Backslash

The sequence \"  inserts a double quote in a string:

Example

var x = "We are the so-called \"Vikings\" from the north.";

The sequence \'  inserts a single quote in a string:

Example

var x = 'It\'s alright.';

The sequence \\  inserts a backslash in a string:

Example

var x = "The character \\ is called backslash.";

Six other escape sequences are valid in JavaScript:

Code

Result

\b

Backspace

\f

Form Feed

\n

New Line

\r

Carriage Return

\t

Horizontal Tabulator

\v

Vertical Tabulator

The 6 escape characters above were originally designed to control typewriters, teletypes, and fax machines. They do not make any sense in HTML.


Breaking Long Code Lines

For best readability, programmers often like to avoid code lines longer than 80 characters.

If a JavaScript statement does not fit on one line, the best place to break it is after an operator:

Example

document.getElementById("demo").innerHTML =
"Hello Dolly!";

You can also break up a code line within a text string with a single backslash:

Example

document.getElementById("demo").innerHTML = "Hello \
Dolly!";

 

The \ method is not the preferred method. It might not have universal support.
Some browsers do not allow spaces behind the 
\ character.

A safer way to break up a string, is to use string addition:

Example

document.getElementById("demo").innerHTML = "Hello " +
"Dolly!";

You cannot break up a code line with a backslash:

Example

document.getElementById("demo").innerHTML = \
"Hello Dolly!";


Strings Can be Objects

Normally, JavaScript strings are primitive values, created from literals:

var firstName = "John";

But strings can also be defined as objects with the keyword new:

var firstName = new String("John");

Example

var x = "John";
var y = new String("John");

// typeof x will return string
// typeof y will return object 

 

Don't create strings as objects. It slows down execution speed.
The 
new keyword complicates the code. This can produce some unexpected results:

When using the == operator, equal strings are equal:

Example

var x = "John";             
var y = new String("John");

// (x == y) is true because x and y have equal values

When using the === operator, equal values may not be equal, because the === operator expects equality in both data type and value.

Example

var x = "John";             
var y = new String("John");

// (x === y) is false because x and y have different types (string and object)

Or even worse. Objects cannot be compared:

Example

var x = new String("John");             
var y = new String("John");

// (x == y) is false because x and y are objects

Example

var x = new String("John");             
var y = new String("John");

// (x === y) is false because x and y are objects

Note the difference between (x==y) and (x===y).
Also note that comparing two JavaScript objects will 
always return false.

 

String Methods and Properties

Primitive values, like "John Doe", cannot have properties or methods (because they are not objects).

But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.

String Length

The length property returns the length of a string:

Example

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;

Finding a String in a String

The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string:

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");

 

JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third ...

The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");

Both indexOf(), and lastIndexOf() return -1 if the text is not found.

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("John");

Both methods accept a second parameter as the starting position for the search:

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate"15);

The lastIndexOf() methods searches backwards (from the end to the beginning), meaning: if the second parameter is 15, the search starts at position 15, and searches to the beginning of the string.

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate"15);

 

Searching for a String in a String

The search() method searches a string for a specified value and returns the position of the match:

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");


Did You Notice?

The two methods, indexOf() and search(), are equal?

They accept the same arguments (parameters), and return the same value?

The two methods are NOT equal. These are the differences:

  • The search() method cannot take a second start position argument.
  • The indexOf() method cannot take powerful search values (regular expressions).

You will learn more about regular expressions in a later chapter.

Extracting String Parts

There are 3 methods for extracting a part of a string:

  • slice(startend)
  • substring(startend)
  • substr(startlength)

The slice() Method

slice() extracts a part of a string and returns the extracted part in a new string.

The method takes 2 parameters: the start position, and the end position (end not included).

This example slices out a portion of a string from position 7 to position 12 (13-1):

Example

var str = "Apple, Banana, Kiwi";
var res = str.slice(713);

The result of res will be:

Banana

Remember: JavaScript counts positions from zero. First position is 0.

If a parameter is negative, the position is counted from the end of the string.

This example slices out a portion of a string from position -12 to position -6:

Example

var str = "Apple, Banana, Kiwi";
var res = str.slice(-12, -6);

The result of res will be:

Banana

If you omit the second parameter, the method will slice out the rest of the string:

Example

var res = str.slice(7);

or, counting from the end:

Example

var res = str.slice(-12);

 

Negative positions do not work in Internet Explorer 8 and earlier.

The substring() Method

substring() is similar to slice().

The difference is that substring() cannot accept negative indexes.

Example

var str = "Apple, Banana, Kiwi";
var res = str.substring(713);

The result of res will be:

Banana

If you omit the second parameter, substring() will slice out the rest of the string.

The substr() Method

substr() is similar to slice().

The difference is that the second parameter specifies the length of the extracted part.

Example

var str = "Apple, Banana, Kiwi";
var res = str.substr(76);

The result of res will be:

Banana

If you omit the second parameter, substr() will slice out the rest of the string.

Example

var str = "Apple, Banana, Kiwi";
var res = str.substr(7);

The result of res will be:

Banana, Kiwi

If the first parameter is negative, the position counts from the end of the string.

Example

var str = "Apple, Banana, Kiwi";
var res = str.substr(-4);

The result of res will be:

Kiwi

Replacing String Content

The replace() method replaces a specified value with another value in a string:

Example

str = "Please visit Microsoft!";
var n = str.replace("Microsoft""W3Schools");

The replace() method does not change the string it is called on. It returns a new string.

By default, the replace() method replaces only the first match:

Example

str = "Please visit Microsoft and Microsoft!";
var n = str.replace("Microsoft""W3Schools");

By default, the replace() method is case sensitive. Writing MICROSOFT (with upper-case) will not work:

Example

str = "Please visit Microsoft!";
var n = str.replace("MICROSOFT""W3Schools");

To replace case insensitive, use a regular expression with an /i flag (insensitive):

Example

str = "Please visit Microsoft!";
var n = str.replace(/MICROSOFT/i, "W3Schools");

Note that regular expressions are written without quotes.

To replace all matches, use a regular expression with a /g flag (global match):

Example

str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/g, "W3Schools");

Converting to Upper and Lower Case

A string is converted to upper case with toUpperCase():

Example

var text1 = "Hello World!";       // String
var text2 = text1.toUpperCase();  // text2 is text1 converted to upper

A string is converted to lower case with toLowerCase():

Example

var text1 = "Hello World!";       // String
var text2 = text1.toLowerCase();  // text2 is text1 converted to lower


The concat() Method

concat() joins two or more strings:

Example

var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ", text2);

The concat() method can be used instead of the plus operator. These two lines do the same:

Example

var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ""World!");

All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced.

String.trim()

The trim() method removes whitespace from both sides of a string:

Example

var str = "       Hello World!        ";
alert(str.trim());

 

The trim() method is not supported in Internet Explorer 8 or lower.

If you need to support IE 8, you can use replace() with a regular expression instead:

Example

var str = "       Hello World!        ";
alert(str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''));

You can also use the replace solution above to add a trim function to the JavaScript String.prototype:

Example

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}
var str = "       Hello World!        ";
alert(str.trim());

Notice that the trim() method is only available since ES5.

ES6 introduced two new methods for removing whitespace characters from a string:

  • trimStart() returns a string with whitespace characters stripped from the beginning of a string.
  • trimEnd() returns a string with the whitespace characters stripped from the end of a string.

JavaScript String Padding

ECMAScript 2017 added two String methods: padStart and padEnd to support padding at the beginning and at the end of a string.

Example

let str = "5";
str = str.padStart(4,0);
// result is 0005

Example

let str = "5";
str = str.padEnd(4,0);
// result is 5000

String Padding is not supported in Internet Explorer.

Firefox and Safari were the first browsers with support for JavaScript string padding:

Extracting String Characters

There are 3 methods for extracting string characters:

  • charAt(position)
  • charCodeAt(position)
  • Property access [ ]

The charAt() Method

The charAt() method returns the character at a specified index (position) in a string:

Example

var str = "HELLO WORLD";
str.charAt(0);            // returns H


The charCodeAt() Method

The charCodeAt() method returns the unicode of the character at a specified index in a string:

The method returns a UTF-16 code (an integer between 0 and 65535).

Example

var str = "HELLO WORLD";

str.charCodeAt(0);         // returns 72

Property Access

ECMAScript 5 (2009) allows property access [ ] on strings:

Example

var str = "HELLO WORLD";
str[0];                   // returns H

 

Property access might be a little unpredictable:

·         It does not work in Internet Explorer 7 or earlier

·         It makes strings look like arrays (but they are not)

·         If no character is found, [ ] returns undefined, while charAt() returns an empty string.

·         It is read only. str[0] = "A" gives no error (but does not work!)

Example

var str = "HELLO WORLD";
str[0] = "A";             // Gives no error, but does not work
str[
0];                   // returns H

 

If you want to work with a string as an array, you can convert it to an array.

Converting a String to an Array

A string can be converted to an array with the split() method:

Example

var txt = "a,b,c,d,e";   // String
txt.split(",");          // Split on commas
txt.split(" ");          // Split on spaces
txt.split("|");          // Split on pipe

If the separator is omitted, the returned array will contain the whole string in index [0].

If the separator is "", the returned array will be an array of single characters:

Example

var txt = "Hello";       // String
txt.split("");           // Split in characters


JavaScript String split() Method


Definition and Usage

The split() method is used to split a string into an array of substrings, and returns the new array.

Tip: If an empty string ("") is used as the separator, the string is split between each character.

Note: The split() method does not change the original string.

Syntax

string.split(separator, limit)

Parameter Values

Parameter

Description

separator

Optional. Specifies the character, or the regular expression, to use for splitting the string. If omitted, the entire string will be returned (an array with only one item)

limit

Optional. An integer that specifies the number of splits, items after the split limit will not be included in the array

 

More Examples

Example

Omit the separator parameter:

var str = "How are you doing today?";
var res = str.split();

Example

Separate each character, including white-space:

var str = "How are you doing today?";
var res = str.split("");

Example

Use the limit parameter:

var str = "How are you doing today?";
var res = str.split(" "3);

Example

Use a letter as a separator:

var str = "How are you doing today?";
var res = str.split("o");

 Matching patterns

The match() method allows you to match a string with a specified regular expression and get an array of results.

The match() method returns null if it does not find any match. Otherwise, it returns an array containing the entire match and any parentheses-capture matched results.

If the global flag (g) is not set, the element zero of the array contains the entire match. Here is an example:

let expr = "1 + 2 = 3";

let matches = expr.match(/\d+/);

console.log(matches[0]); // "1"

In this example, the pattern matches any number in the expr string.

In case the global flag ( g) is set, the elements of the result array contain all matches as follows:

matches = expr.match(/\d+/g);

matches.forEach(function(m) {

    console.log(m);

});

// "1"

// "2"

// "3"

In this example, the matches array contains all matches including 1, 2 and 3 in the  expr string.

In case you only need to find out if a string matches a regular expression, you use the search() method instead.

Similar to the match() method, the search() method accepts a regular expression and returns the position of the string where the first match found. In case no match is found, it returns -1.

let str = "This is a test of search()";

let pos = str.search(/is/);

console.log(pos); // 2

String includes() Method

The includes() method determines whether a string contains another string:

string.includes(searchString [,position])

The includes() method returns true if the searchString found in the string; otherwise false.

The optional position parameter specifies the position within the string at which to begin searching for the searchString. The position defaults to 0.

The includes() matches string case-sensitively.

JavaScript String includes() examples

This example uses the includes() method to check if the string @ is in the string 'admin@example.com':

let email = 'admin@example.com';

console.log(email.includes('@'));

The following example checks if the str contains the Script:

let str = 'JavaScript String';

console.log(str.includes('Script'));

As mentioned earlier, the includes() matches the string case-sensitively, therefore, the following example returns false:

False

The following example uses the includes() method with the second parameter:

let str = 'JavaScript String';

console.log(str.includes('Script', 5));

Complete String Reference

For a complete reference, go to our Complete JavaScript String Reference.

The reference contains descriptions and examples of all string properties and methods.

 

 

No comments:

Post a Comment