Home » JavaScript String Methods

JavaScript String Methods

JavaScript String Methods

JavaScript string methods are functions that you can use on strings (text). They allow you to manipulate, search, or modify strings in various ways without having to write complex logic from scratch. Here are some commonly used JavaScript string methods

toUpperCase Method

Some websites offer a feature that allows you to convert all the provided text into uppercase. How is this achieved?

toUpperCase-Methods-Javascripts.png

You can do this by using toUpperCase().

let s = "I love Geekster";
let s1 = s.toUpperCase();
console.log(s1); // I LOVE GEEKSTER
JavaScript

toLowerCase Method

There is a feature on the website that can convert text into lowercase. How is this accomplished?

toLowerCase-Methods-JavaScript.png

You can do this by using toLowerCase().

let s = "I love Geekster";
let s1 = s.toLowerCase();
console.log(s1); // i love geekster
JavaScript

String Search Method

When you need to find a specific word within a Word document, how does the search process work?

You can do by using search() method.

The search() method returns the index of the first occurrence of the substring in the string, or -1 if the substring is not found.

let text = "Hi there today we will learn about String and its method let’s see:-";
let keyword = "about";
let position = text.search(keyword);
if (position !== -1) {
  console.log(`The keyword "${keyword}" was found at position ${position}.`);
} else {
  console.log(`The keyword "${keyword}" was not found in the text.`);
}
JavaScript

Output:-

The keyword "about" was found at position 29.
JavaScript

String Replace Method

You can replace any word in docs. How can you do that? let’s see

String-Replace-Methods-JavaScript.png

The replace() method in JavaScript is used to replace a specified substring or regular expression pattern in a string with another string. It returns a new string with the replacement performed, leaving the original string unchanged.

let text = "Hi there today we will learn about String and its method let’s see:-";
let keyword = "about";
const replacedText1 = text.replace(keyword, "Something");
console.log(replacedText1); // Output: "Hi there today we will learn Something String and its method let’s see:-"
JavaScript

String Slice Method

We have come across websites where that display some text, followed by a ‘Continue Reading’ option. How to Cut and Show half String ? How is this achieved? Let’s take a closer look

String-Slice-Method.png

here comes the slice Method.

The slice() method in JavaScript is used to extract a portion of a string and create a new string with the extracted characters. It takes two arguments: the start index and the optional end index. Here’s an explanation of how the slice() method works:

  • start (required): The index at which the extraction begins. This position is inclusive, meaning the character at the start index is included in the result.
  • end (optional): The index where the extraction ends. This position is exclusive, meaning the character at the end index is not included in the result. If you omit the end argument, the extraction continues to the end of the string

Example:-

let text = "I've been developing WordPress themes for more
 than 2 years and based from my own experience and personal 
preferences, here are the most common WordPress code snippets
 that I use. Please do check it out and you learn a thing or two, 
let me know in the comments. carbon.sh, VsCode"
let sliceText = text.slice(0,261)
console.log(sliceText+"..") 
"Output:- I've been developing WordPress themes for more
 than 2 years and based from my own experience and personal 
preferences, here are the most common WordPress code snippets 
that I use. Please do check it out and you learn a thing or two,
 let me know in the comments..."
JavaScript

String Substring Method

We were using the slice method to accomplish that task, but we can also achieve it using the substring method. Let’s explore this approach.

The substring() method in JavaScript is used to extract a portion of a string and create a new string with the extracted characters. It takes two arguments: the start index and the optional end index. Here’s an explanation of how the substring() method works:

  • start (required): The index at which the extraction begins. This position is inclusive, meaning the character at the start index is included in the result.
  • end (optional): The index where the extraction ends. This position is exclusive, meaning the character at the end index is not included in the result. If you omit the end argument, the extraction continues to the end of the string.
let text = "I've been developing WordPress themes for more
than 2 years and based from my own experience and personal 
preferences, here are the most common WordPress code snippets
that I use. Please do check it out and you learn a thing or two, 
let me know in the comments. carbon.sh, VsCode"
let sliceText = text.substring(0,87)
console.log(sliceText+"..") 
// I've been developing WordPress themes for more than 2 years and
// based from my own exper..
JavaScript

Example 2:-

let text = "Hello, World!";
let subText1 = text.substring(0, 5);
console.log(subText1); // Output: "Hello"

let subText2 = text.substring(7); // If no end index is provided, it goes to the end
console.log(subText2); // Output: "World!"

let subText3 = text.substring(6, 0); // Reversing the order of 'start' and 'end'
console.log(subText3); // Output: "Hello" (start is inclusive, end is exclusive)

let subText4 = text.substring(7, 12); // End index goes beyond the actual end
console.log(subText4); // Output: "World!" (it stops at the end)

let subText5 = text.substring(-5); // Negative index is treated as 0
console.log(subText5); // Output: "Hello, World!"
JavaScript
let text = "Hello, World!";
let slicedText1 = text.slice(0, 5)
console.log(slicedText1); // Output: "Hello"

let slicedText2 = text.slice(7); // If no end index is provided, it goes to the end
console.log(slicedText2); // Output: "World!"

let slicedText3 = text.slice(-6); // Negative index counts from the end of the string
console.log(slicedText3); // Output: "World!"

let slicedText4 = text.slice(7, -1); // Negative index for 'end' also counts from the end
console.log(slicedText4); // Output: "World"
JavaScript

String Substr Method

We have used both the slice and substring methods to complete the task. Another method we can explore is substr. Let’s see how it works.

The substr() method in JavaScript is used to extract a portion of a string and create a new string with the extracted characters. It takes two arguments: the start index and the optional length. Here’s an explanation of how the substr() method works:

  • start (required): The index at which the extraction begins. This position is inclusive, meaning the character at the start index is included in the result.
  • length (optional): The number of characters to extract from the string, starting at the start index. If you omit the length argument, the extraction continues to the end of the string.
let text = "I've been developing WordPress themes for more
 than 2 years and based from my own experience and personal 
preferences, here are the most common WordPress code snippets
 that I use. Please do check it out and you learn a thing or two, 
let me know in the comments. carbon.sh, VsCode"
let sliceText = text.substr(0,87)
console.log(sliceText+"..") 
// I've been developing WordPress themes for more than 2 years and
// based from my own exper..
JavaScript

Example 2:-

let text = "Hello, World!";
let subStr1 = text.substr(0, 5);
console.log(subStr1); // Output: "Hello"

let subStr2 = text.substr(7); // If no length is provided, it goes to the end
console.log(subStr2); // Output: "World!"

let subStr3 = text.substr(7, 3); // Starts at index 7 and extracts 3 characters
console.log(subStr3); // Output: "Wor"

let subStr4 = text.substr(-6); // Negative index counts from the end of the string
console.log(subStr4); // Output: "World!"

let subStr5 = text.substr(20); // If 'start' exceeds the string length, it returns an empty string
console.log(subStr5); // Output: ""
JavaScript

Conclusion

JavaScript string methods like toUpperCase(), toLowerCase(), search(), replace(), slice(), substring(), and substr() offer powerful tools for manipulating and querying text. These functions enable developers to perform tasks ranging from text formatting and content modification to substring extraction and search functionalities with ease. Choosing the appropriate method depends on the specific needs of the task at hand, such as the requirement for handling negative indices or the need to specify substring length. Utilizing these methods enhances code efficiency and readability in text-processing applications.

Frequently Asked Questions

Q1. What’s the difference between slice(), substring(), and substr() methods?

Ans: slice() allows for extraction based on a start and end index, with support for negative indices counting from the end of the string.
substring() extracts characters between two indices, not allowing negative indices and treating them as 0.
substr() has been deprecated and is not recommended for use in new code. It extracts a substring starting at a given index with a specified length, with support for a negative start index counting from the end.


Q2. Can replace() the method change the original string?

Ans: No, the replace() method does not alter the original string. It returns a new string with the specified modifications, leaving the original string unchanged.


Q3. How can I convert a string to uppercase or lowercase?

Ans: To convert a string to uppercase, use the toUpperCase() method. For converting to lowercase, use the toLowerCase() method. Both methods return a new string with the conversion applied.


Q4. Is there a performance difference between slice(), substring(), and substr()?

Ans: The performance differences between these methods are generally negligible for most practical applications. The choice between them should be based on their functionality and compatibility rather than performance.


Q5. Why might search() method return -1?

Ans: The search() method returns -1 if the specified substring or pattern is not found within the string. It indicates that the search was unsuccessful.