In javascript using length
property we can find the length of a string.
The length
property returns the length of a string (number of characters).
For example:
const myString = "Hello, CSC!";
console.log(myString.length);
There are many methods available for manipulating strings in JavaScript. Let's explore some of the most commonly used string methods one by one.
charAt()
Returns the character at a specified index in the string.
const myString = "Hello, CSC!";
console.log(myString.charAt(0));
concat()
Joins two or more strings together.
const myString = "Hello";
const anotherString = ", CSC!";
console.log(myString.concat(anotherString));
indexOf()
Returns the index of the first occurrence of a specified substring in the string.
const myString = "Hello, CSC!";
console.log(myString.indexOf("CSC"));
slice()
Extracts a portion of the string and returns it as a new string.
const myString = "Hello, CSC!";
console.log(myString.slice(7));
toUpperCase()
Converts the string to uppercase.
const myString = "Hello, CSC!";
console.log(myString.toUpperCase());
toLowerCase()
Converts the string to lowercase.
const myString = "Hello, CSC!";
console.log(myString.toLowerCase());
split()
Splits a string into an array of substrings based on a specified delimiter.
const myString = "Hello, CSC!";
console.log(myString.split(","));
replace()
Replaces a substring in the string with another substring.
const myString = "Hello, CSC!";
console.log(myString.replace("CSC", "UpSkillers"));
Template literals
A syntax for creating strings that allows for variable interpolation and multi-line strings.
Template literals are enclosed in backticks "(`)" and variables are wrapped in "${}".
const name = "CSC";
console.log(`Hello, ${name}!
How are you today?`);
String methods that return a boolean
value
startsWith()
, endsWith()
, and includes()
are the methods that return a boolean
value.
These methods can be used to check if a string starts, ends, or includes a specified substring.
const myString = "Hello, CSC!";
console.log(myString.startsWith("Hello"));
console.log(myString.endsWith("CSC!"));
console.log(myString.includes("UpSkillers"));
JavaScript String trim()
The trim()
method in JavaScript is used to remove whitespace (spaces, tabs, and line breaks) from both ends of a string.
It returns a new string with the whitespace removed. The original string is not modified.
Example of how to use trim()
:
const myString = ' Hello, CSC! ';
console.log(myString.trim());
String Methods - Example
JavaScript strings are immutable, meaning that once a string is created, it cannot be changed. However, the methods provided by JavaScript can be used to manipulate strings and create new strings based on existing ones.