CS Engineering Gyan

JavaScript Strings

Strings are one of the most commonly used data types in JavaScript. A string represents a sequence of characters such as letters, numbers, symbols, and spaces.

Almost every web application works with text data. User names, passwords, messages, search keywords, product descriptions, and website content are all handled using strings.

JavaScript provides many built-in features to create, modify, search, and manipulate strings efficiently.


What is a String in JavaScript?

A string is a collection of characters enclosed inside single quotes, double quotes, or backticks.

Example


let name = "Rahul";

let city = 'Delhi';

let message = `Welcome`;

All three values are strings in JavaScript.


Why are Strings Important?

Strings are essential because most programs need to process text information.

Applications of Strings


Creating Strings in JavaScript

JavaScript provides three different ways to create strings.


1. Using Double Quotes

Strings can be created by placing text inside double quotation marks.

Example


let language = "JavaScript";


document.write(language);

Output


JavaScript


2. Using Single Quotes

Single quotes can also be used to create strings.

Example


let course = 'Web Development';


document.write(course);

Output


Web Development


3. Using Template Literals

Template literals use backticks (`) and allow embedding variables directly inside strings.

Example


let name = "Amit";


let message = `Hello ${name}`;


document.write(message);

Output


Hello Amit


String with Quotes Inside Text

When a string contains quotation marks, escape characters can be used.

Example


let text = "JavaScript is \"easy\"";


document.write(text);

Output


JavaScript is "easy"


Escape Characters in Strings

Escape characters are special characters used to represent characters that cannot be directly written inside a string.

Escape Character Description
\' Single Quote
\" Double Quote
\\ Backslash
\n New Line
\t Tab Space

Finding String Length

The length property returns the total number of characters present inside a string.

Example


let text = "JavaScript";


document.write(text.length);

Output


10


Accessing String Characters

Characters inside a string can be accessed using index numbers. String indexing starts from zero.

Example


let language = "JavaScript";


document.write(language[0]);

Output


J


String Indexing

Character Index
J 0
a 1
v 2
a 3
S 4

Changing String Characters

Strings in JavaScript are immutable, which means individual characters cannot be directly changed.

Example


let name = "Rahul";


name[0] = "M";


document.write(name);

Output


Rahul

A new string must be created if changes are required.


String Concatenation

String concatenation means joining two or more strings together.

Using + Operator


let first = "Java";

let second = "Script";


let result = first + second;


document.write(result);

Output


JavaScript


Concatenation Using concat() Method


let first = "Hello ";

let second = "World";


let result = first.concat(second);


document.write(result);

Output


Hello World



JavaScript String Methods

JavaScript provides many built-in string methods that help developers perform different operations on text data. These methods make it easier to search, modify, extract, and format strings.

String methods do not change the original string because strings are immutable. Instead, they return a new string with the required changes.


charAt() Method

The charAt() method returns the character present at a specific index position in a string.

Syntax


string.charAt(index);

Example


let text = "JavaScript";


document.write(text.charAt(4));

Output


S


charCodeAt() Method

The charCodeAt() method returns the Unicode value of a character at a specified position.

Example


let text = "A";


document.write(text.charCodeAt(0));

Output


65


includes() Method

The includes() method checks whether a string contains a specific word or character.

It returns true if the value exists; otherwise, it returns false.

Example


let message = "Welcome to JavaScript";


document.write(message.includes("JavaScript"));

Output


true


indexOf() Method

The indexOf() method returns the first position of a specified value inside a string.

Example


let text = "Programming";


document.write(text.indexOf("g"));

Output


3

If the value is not found, the method returns -1.


lastIndexOf() Method

The lastIndexOf() method returns the last occurrence position of a specified value.

Example


let text = "JavaScript";


document.write(text.lastIndexOf("a"));

Output


3


startsWith() Method

The startsWith() method checks whether a string begins with a specific value.

Example


let text = "JavaScript";


document.write(text.startsWith("Java"));

Output


true


endsWith() Method

The endsWith() method checks whether a string ends with a specific value.

Example


let text = "JavaScript";


document.write(text.endsWith("Script"));

Output


true


toUpperCase() Method

The toUpperCase() method converts all characters of a string into uppercase letters.

Example


let text = "javascript";


document.write(text.toUpperCase());

Output


JAVASCRIPT


toLowerCase() Method

The toLowerCase() method converts all characters of a string into lowercase letters.

Example


let text = "JAVASCRIPT";


document.write(text.toLowerCase());

Output


javascript


trim() Method

The trim() method removes extra spaces from the beginning and end of a string.

Example


let text = "   Hello World   ";


document.write(text.trim());

Output


Hello World


trimStart() Method

The trimStart() method removes spaces only from the beginning of a string.

Example


let text = "   JavaScript";


document.write(text.trimStart());

Output


JavaScript


trimEnd() Method

The trimEnd() method removes spaces from the end of a string.

Example


let text = "JavaScript   ";


document.write(text.trimEnd());

Output


JavaScript


slice() Method

The slice() method extracts a part of a string and returns a new string.

Syntax


string.slice(start,end);

Example


let text = "JavaScript";


document.write(text.slice(0,4));

Output


Java


substring() Method

The substring() method extracts characters between two indexes.

Example


let text = "Programming";


document.write(text.substring(0,7));

Output


Program


Difference Between slice() and substring()

slice() substring()
Supports negative indexes. Does not support negative indexes.
Can extract from end using negative values. Treats negative values as zero.
Works with strings and arrays. Mainly used with strings.

substr() Method

The substr() method extracts a part of a string using starting position and length.

Example


let text = "JavaScript";


document.write(text.substr(4,6));

Output


Script

The substr() method is considered an older method. Modern applications generally prefer slice() or substring().


replace() Method

The replace() method replaces a specific value with another value in a string.

Example


let text = "I like Java";


let result = text.replace("Java","JavaScript");


document.write(result);

Output


I like JavaScript


replaceAll() Method

The replaceAll() method replaces all occurrences of a value inside a string.

Example


let text = "Java Java Java";


let result = text.replaceAll("Java","Python");


document.write(result);

Output


Python Python Python


split() Method

The split() method converts a string into an array based on a separator.

Example


let text = "HTML,CSS,JavaScript";


let result = text.split(",");


document.write(result[1]);

Output


CSS


repeat() Method

The repeat() method creates a new string by repeating an existing string multiple times.

Example


let text = "Hi ";


document.write(text.repeat(3));

Output


Hi Hi Hi


String Comparison

JavaScript allows comparison between strings using comparison operators.

Example


let a = "JavaScript";

let b = "JavaScript";


document.write(a == b);

Output


true



Template Literals in JavaScript

Template literals are a modern way to create strings in JavaScript. They were introduced in ES6 and use backticks (`) instead of single or double quotes.

Template literals make string creation easier because they support variable insertion, expressions, and multiline text.

Example


let name = "Rahul";


let message = `Hello ${name}`;


document.write(message);

Output


Hello Rahul


String Interpolation

String interpolation means inserting variables or expressions directly inside a string using the ${ } syntax.

It is only supported inside template literals.

Example: Variable Interpolation


let name = "Amit";

let age = 20;


let result = `My name is ${name} and my age is ${age}`;


document.write(result);

Output


My name is Amit and my age is 20


Expression Inside Template Literals

Template literals can execute JavaScript expressions directly inside strings.

Example


let a = 10;

let b = 20;


let result = `Sum = ${a+b}`;


document.write(result);

Output


Sum = 30


Multiline Strings

Traditional strings require escape characters for multiple lines, but template literals allow multiline strings directly.

Example


let message = `Welcome to
JavaScript
Tutorial`;


document.write(message);

Output


Welcome to
JavaScript
Tutorial


String Conversion in JavaScript

JavaScript allows converting different data types into strings using built-in methods.


Using String() Method

The String() method converts any value into a string.

Example


let number = 123;


let result = String(number);


document.write(typeof result);

Output


string


Using toString() Method

The toString() method converts numbers, arrays, and objects into strings.

Example


let number = 500;


document.write(number.toString());

Output


500


Converting String to Number

JavaScript provides methods to convert numeric strings into numbers.

Using Number()


let value = "100";


let result = Number(value);


document.write(result + 50);

Output


150


Using parseInt()

The parseInt() method converts a string into an integer number.

Example


let value = "250";


let result = parseInt(value);


document.write(result);

Output


250


Using parseFloat()

The parseFloat() method converts a string containing decimal values into a floating-point number.

Example


let price = "99.50";


let result = parseFloat(price);


document.write(result);

Output


99.5


Checking String Content

JavaScript provides different methods to check whether specific text exists inside a string.

Method Description
includes() Checks whether text exists.
startsWith() Checks starting characters.
endsWith() Checks ending characters.
indexOf() Returns position of text.
search() Searches using patterns.

search() Method

The search() method searches a string for a specified value or regular expression.

Example


let text = "Learn JavaScript";


document.write(text.search("JavaScript"));

Output


6


match() Method

The match() method searches a string and returns matching results based on a pattern.

Example


let text = "JavaScript is powerful";


let result = text.match("JavaScript");


document.write(result);

Output


JavaScript


Regular Expressions with Strings

Regular expressions are patterns used to search and manipulate text.

They are commonly used for email validation, password checking, and searching complex patterns.

Example


let text = "JavaScript123";


let result = text.match(/[0-9]+/);


document.write(result);

Output


123


Practical String Programs


Program 1: Reverse a String


let text = "JavaScript";


let reverse = text.split("")
.reverse()
.join("");


document.write(reverse);

Output


tpircSavaJ


Program 2: Count Characters in String


let text = "Programming";


document.write(text.length);

Output


11


Program 3: Check Palindrome String


let text = "madam";


let reverse = text.split("")
.reverse()
.join("");


if(text == reverse)
{

document.write("Palindrome");

}

else
{

document.write("Not Palindrome");

}

Output


Palindrome


Program 4: Count Vowels in String


let text = "JavaScript";


let count = 0;


for(let char of text)
{

if("aeiouAEIOU".includes(char))
{

count++;

}

}


document.write(count);

Output


3


Real-World Applications of JavaScript Strings

Strings are used in almost every web application for handling text-based information.


Common Mistakes While Working with Strings


Best Practices for JavaScript Strings


JavaScript Strings Interview Questions

  1. What is a string in JavaScript?
  2. How can you create strings?
  3. What is the difference between string and number data types?
  4. Explain string immutability.
  5. What is template literal?
  6. What is string interpolation?
  7. Explain slice() and substring().
  8. Difference between replace() and replaceAll().
  9. What is the use of split() method?
  10. How do you reverse a string?
  11. How can you check if a string contains a value?
  12. Explain trim() method.
  13. What are escape characters?
  14. Difference between String() and toString().
  15. How are regular expressions used with strings?

Summary

JavaScript strings are used to store and manipulate text data. They provide powerful methods for searching, modifying, formatting, and processing information.

Important string concepts include string creation, indexing, concatenation, template literals, conversion, searching methods, replacement methods, and regular expressions.

A strong understanding of strings helps developers build interactive websites, validate user data, process information, and work efficiently with modern JavaScript applications.


← Previous: JavaScript Objects Next: JavaScript Events →
Home Visit Our YouTube Channel