JavaScript - String




JavaScript - String

Strings are values made up of text and can contain letters, numbers, symbols, punctuation, and even emoji. Strings are contained within a pair of either single quotation marks '' or double quotation marks "".

'This is a string. πŸ‘';
"This is the 2nd string. πŸ’";

JavaScript strings are primitive values. JavaScript strings are also immutable. It means that if you process a string, you will always get a new string. The original string doesn’t change. To create literal strings in JavaScript, you use single quotes or double quotes:

let str = 'Hi';
let greeting = "Hello";

ES6 introduced template literals that allow you to define a string backtick (`) characters:

let name = 'John';
let message `Hello ${name}`;

console.log(greeting);

Output

Hello John

The string message evaluates the name variable and returns the result string.

Escaping special characters

To escape special characters, you use the backslash \ character. For example -

Windows line break: '\r\n'
Unix line break: '\n'
Tab: '\t'
Backslash '\'

The following example uses the backslash character to escape the single quote character in a string -

let str = 'I\'m a string!';

JavaScript String

Strings are simply groups of characters, like 'JavaScript', 'Hello world!', When you write JavaScripts, you need to know what strings are and how they work. You'll use them a lot, since most things you can read out (the URL of a page, a style sheet declaration, the value of a form field) are strings. First I explain the basics of strings. Then I explain the fuzzy line between strings and numbers in JavaScript. If you have programming experience in another language, please read this part carefully. Finally I give some of the most important methods and properties of strings.

String basics

Let's review the basics of strings.

When you declare and manipulate strings in JavaScript, always write them with single quotes ' or double quotes " around them. This tells the browser that it's dealing with a string. Don't mix up your quotes, if you start a string with a single quote and end it with a double quote, JavaScript doesn't understand what you mean. As a rule, I use single quotes ' because I've decided to use double quotes for HTML and single quotes for JavaScript. You can of course do this the other way around, but I advise you to make some such rule for yourself.

Let's introduce our two test strings that we'll use throughout this page -

var a = 'Hello world!';
var b = 'I am a JavaScript hacker.'

Now we have declared two variables, a and b and put strings in them. Having done this, we can start working with them. But first of all, a problem: suppose I'd written.

var b = 'I'm a JavaScript hacker.';

This string has a single quote in it, so JavaScript thinks that the string ends, doesn't understand what comes next and gives error messages. So you need to escape the single quote, telling the browser to treat the quote as a character, and not as a command to end the string. This is done by placing a backslash \ before it -

var b = 'I\'m a JavaScript hacker.'

Note that you can put double quotes in the string without escaping them. After all, you've defined the single quotes as the beginning and end of the string, so.

var b = 'I\'m a JavaScript "hacker".'

gives no problems. The double quotes are automatically treated as parts of the string, not as commands.

String length property

JavaScript String length property return the number of characters in a string.

var str = "ABCDE";
var len = str.length;
alert(len);

Output

5

charAt(index)

charAt() is a method that returns the character from the specified index.

var str = "ABCDE";
alert(str.charAt(0));
alert(str.charAt(4))

Output

A and D

Examples of String Functions in JavaScript

Below are the examples -

IndexOf()

It will search and will return the index of the first occurrence of a mentioned character or substring within the string. If mentioned character or substring is not found, it will return -1.

var st = "Please only find where 'only' occurs!";
var po = st.indexOf("only");

indexOf() method will return the position of the first occurrence of the mentioned text, that is, 7.

lastIndexOf()

This JavaScript String function will search and return the index of the last occurrence of a mentioned character or substring within the string. If mentioned character or substring is not found, it will return -1

var st = "Please only find where 'only' occurs!";
var po = st.lastindexOf("only");

lastIndexOf() method will return the position of the last occurrence of mentioned text, that is, 23

search()

It will search and test for a match in a string and returns the index of the match. If mentioned character or substring is not found, it will return -1.

var st = "Please only find where 'only' occurs!";
var po = st.search("only");

search() method will return the position of the first occurrence of the mentioned text, that is, 7. The difference between the search() method and indexOf() method is that the search() method cannot take the second argument and indexOf() method cannot take regular expressions.

slice()

This string function in JavaScript is used to trims a part of a string and returns the trimmed part in a newly created string.

var string = "Mango, Apple, Kiwi";
var r = string.slice(7, 12);

The result of r will be: Apple

var s = "Apple, Kiwi";
var r = s.slice(-10, -6);

The result of r will be: Kiwi

charAt(y)

Returns the character that is located at the β€œy” position in the string.

var s = "WORLD";
var r = s.charAt(3);

The result of r will be: L

charCodeAt(y)

This method will return the Unicode value of the character that is located at position β€œy” in the string.

var str = "Halloween";
var r = str.charCodeAt(0);

The result of r will be: 72