Introduction
In JavaScript, a string is a sequence of characters used to represent text. Strings are one of the fundamental data types in JavaScript and are commonly used to store and manipulate textual data.
String can be enclosed in Single Quotes like ‘john’ or Double Quotes like “john” or backtics (which came into ES6) like `john`.
What is a JavaScript String?
A String in JavaScript is a sequence of characters enclosed inside quotes. It can contain letters, numbers, symbols, and spaces.
JavaScript supports three ways to create strings:
- Single quotes (”)
- Double quotes (“”)
- Template literals ( )
Syntax of JavaScript String
let variableName = 'value';
//or
let variableName = "value";
//or
let variableName = `value`;
Example:
let name = 'John';
let city = "Delhi";
let message = `Welcome to JavaScript`;
Creating Strings in JavaScript
You can create a string in the following ways.
1. Using Double Quotes
let name = "John";
console.log(name);
Output:
2. Using Single Quotes
let city = 'Delhi';
console.log(city);
Output:
3. Using Template Literals
Template literals support variables and multiline strings.
let name = "John";
console.log(`Hello ${name}`);
Output:
4. Using String() Method
You can create a string through the String() function.
var age=35;
var age_string=String(age);
console.log(age_string); // Output:- "35"
Output:
5. Using toString() Method
toString() is used to convert data into a string.
var age =35;
var age_string=age.toString();
console.log(age_string); // Output:- "35"
Output:
6. Using a new keyword
Creating a String Object through the new keyword, and it behaves like an Object.
var string_object = new String("John");
console.log(string_object);
console.log(string_object.toString());
console.log(string_object.valueOf());
Output:
John
John
JavaScript String Methods
Strings provide built-in methods for manipulating text.
1. length Property
It returns the total number of characters.
let text = "John";
console.log(text.length);
Output:
2. toUpperCase() Method
It converts text into uppercase.
let name = "john";
console.log(name.toUpperCase());
Output:
3. toLowerCase() Method
It converts text into lowercase.
let city = "DELHI";
console.log(city.toLowerCase());
Output:
4. trim() Method
It removes extra spaces.
let str = " Hello ";
console.log(str.trim());
Output:
5. includes() Method
It checks whether text exists.
let msg = "Learn JavaScript";
console.log(msg.includes("Java"));
Output:
6. replace() Method
It replaces characters or words.
let text = "I like Java";
console.log(text.replace("Java","JavaScript"));
Output:
7. slice() Method
It extracts part of a string.
let word = "Hello World";
console.log(word.slice(0,4));
Output:
8. split() Method
It converts a string into an array.
let fruits = "Apple,Banana,Mango";
console.log(fruits.split(","));
Output:
How to Concatenate a String
Combining multiple strings is called concatenation.
1. Using + to add Multiple Strings
Example:
let firstName = "John";
let lastName = "Taylor";
console.log(firstName + " " + lastName);
Output:
2. Using template literals:
let first = "John";
let last = "Taylor";
console.log(`${first} ${last}`);
Output:
Escape Characters in Strings
Escape characters allow special formatting.
Example:
let text = "He said \"Hello\"";
console.log(text);
Output:
Common escape characters:
| Escape Character | Meaning | Example Output |
|---|---|---|
\n |
New Line | Moves text to next line |
\t |
Tab | Adds horizontal space |
\" |
Double Quote | Prints ” inside string |
\' |
Single Quote | Prints ‘ inside string |
\\ |
Backslash | Prints \ |
Example of JavaScript String
Example 1: Display User Name
let username = "John";
console.log("Welcome " + username);
Output:
Example 2: Find String Length
let course = "JavaScript";
console.log(course.length);
Output:
Example 3: Convert Uppercase
let name = "John";
console.log(name.toUpperCase());
Output:
String can be enclosed in Single Quotes like ‘john’ or Double Quotes like “john” or backtics (which came into ES6) like `john`.
var first_name ='John';
var last_name="Taylor";
var email=`john@abc.com`;
Note:- backtics is basically used to combined variable value and strings.
Example:- Now you add first_name and last_name along with Hello string.
var full_name=`Hello ${first_name} ${last_name}`;
console.log(full_name); // Output:- John Taylor
Create a String:-
1) String():- You can create string through String function.
var age=35;
var age_string=String(age);
console.log(age_string); // Output:- "35"
var bool =true;
var bool_string=String(bool) // Output:- "true"
2) toString():- toString() is used to convert data into string.
var age =35;
var age_string=age.toString(); // Output "35";
var bool =true;
var bool_string=bool.toString() // Output:- "true"
3) creating a String Object through new keyword and it behaves like Object
var string_object = new String("John");
console.log(typeof string_object); //output:- "object"
Concat two or more strings:- 1) You can concat the two string through + sign
var first_name="John";
var last_name="Taylor";
document.write(first_name + last_name); //Output:- JohnTaylor
document.write(first_name +' '+last_name); //Output:- John Taylor
2) You can concat strings through concat() keyword.
var first_name="John";
var last_name="Taylor";
document.write(first_name.concat(last_name)); //Output:- JohnTaylor
3) Concat string through backtics
var first_name="John";
var last_name="Taylor";
document.write(`${first_name} ${last_name}`); //Output:- John Taylor
trim() method:- this method is used to trim the white space from the string.
var name=" John ";
console.log(name.trim()); //Output:- John
split() method:- It is used to split a string into Array
var str="John went to college";
var str_arr=str.split(" ");
document.write(str_arr[0]); // Output:- John
document.write(str_arr[1]); // Output:- went
document.write(str_arr[2]); // Output:- to
document.write(str_arr[3]); // Output:- college
join() method:- It is used convert Array into String
arr=["John", "went", "to", "college"];
arr_to_string= arr.join("-");
document.write(arr_to_string); // Output:- John-went-to-college
Reverse a string:-
var str="John Taylor"
let rev_string= str.split('').reverse().join('');
document.write(rev_string); // Output:- rolyaT nhoJ
Javascript String – Interview Questions
Q 1: What is a string?
Q 2: How to define a string?
Q 3: Are strings immutable?
Q 4: How to find the string length?
Q 5: How to convert to uppercase?
Javascript String – Objective Questions (MCQs)
Q1. Strings in JavaScript are written inside ______.
Q2. Which method returns string length?
Q3. Which is a valid string?
Q4. Which method converts string to uppercase?
Q5. JavaScript strings are ______.