Logo

dev-resources.site

for different kinds of informations.

Mastering String Operations in JavaScript πŸš€

Published at
11/16/2024
Categories
javascript
beginners
tutorial
string
Author
prithwish249
Author
12 person written this
prithwish249
open
Mastering String Operations in JavaScript πŸš€

Strings are a core part of programming in JavaScript, and working with them efficiently can make your applications more dynamic and powerful. Whether you’re building complex applications or writing simple scripts, understanding string operations is a must-have skill. Here’s an in-depth guide to mastering string operations in JavaScript. 🌟


1. String Concatenation 🧡

Concatenation combines two or more strings into one. JavaScript offers multiple ways to achieve this:

Using + Operator:

let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName; // "John Doe"
Enter fullscreen mode Exit fullscreen mode

Using Template Literals (ES6):

Template literals allow for embedding variables and expressions inside strings, making them more flexible.

let age = 30;
let introduction = `${firstName} ${lastName} is ${age} years old.`;
console.log(introduction); // "John Doe is 30 years old."
Enter fullscreen mode Exit fullscreen mode

Performance Tip:

For concatenating many strings in loops, consider using Array.prototype.join() for better performance.


2. String Length πŸ”’

The .length property returns the total number of characters in a string, including spaces and punctuation.

let text = "Hello, World!";
console.log(text.length); // 13
Enter fullscreen mode Exit fullscreen mode

3. Changing Case πŸ”

JavaScript provides .toUpperCase() and .toLowerCase() for case conversions. These are useful for creating case-insensitive comparisons.

let original = "JavaScript";
console.log(original.toUpperCase()); // "JAVASCRIPT"
console.log(original.toLowerCase()); // "javascript"

// Case-insensitive comparison
let input = "javascript";
console.log(input.toLowerCase() === original.toLowerCase()); // true
Enter fullscreen mode Exit fullscreen mode

4. Extracting Substrings βœ‚οΈ

You can extract parts of a string using .slice(), .substring(), or .substr().

Using .slice(start, end):

  • Extracts characters from start index to end index (excluding end).
let greeting = "Hello, World!";
console.log(greeting.slice(7, 12)); // "World"
console.log(greeting.slice(-6));   // "World!"
Enter fullscreen mode Exit fullscreen mode

Using .substring(start, end):

  • Similar to .slice(), but doesn’t support negative indices.
console.log(greeting.substring(7, 12)); // "World"
Enter fullscreen mode Exit fullscreen mode

Using .substr(start, length) (Deprecated):

  • Extracts length characters starting from start.
console.log(greeting.substr(7, 5)); // "World"
Enter fullscreen mode Exit fullscreen mode

5. Searching for Substrings πŸ”

Search for substrings in strings using .indexOf(), .lastIndexOf(), and .includes().

.indexOf(substring, start):

Finds the first occurrence of a substring, starting from the start index. Returns -1 if not found.

let sentence = "JavaScript is great!";
console.log(sentence.indexOf("is")); // 11
console.log(sentence.indexOf("Python")); // -1
Enter fullscreen mode Exit fullscreen mode

.lastIndexOf(substring, start):

Finds the last occurrence of a substring.

console.log(sentence.lastIndexOf("a")); // 3
Enter fullscreen mode Exit fullscreen mode

.includes(substring, start):

Checks if a substring exists in the string (returns true or false).

console.log(sentence.includes("great")); // true
console.log(sentence.includes("bad")); // false
Enter fullscreen mode Exit fullscreen mode

6. Replacing Substrings πŸ”„

Replace specific parts of a string using .replace() or .replaceAll() (introduced in ES2021).

.replace():

Replaces the first occurrence of a substring or a regex match.

let phrase = "I love Java!";
console.log(phrase.replace("Java", "JavaScript")); // "I love JavaScript"
Enter fullscreen mode Exit fullscreen mode

.replaceAll():

Replaces all occurrences of a substring.

let repeated = "apple apple apple";
console.log(repeated.replaceAll("apple", "banana")); // "banana banana banana"
Enter fullscreen mode Exit fullscreen mode

7. Trimming Whitespaces ✨

Remove unnecessary whitespaces using .trim(), .trimStart(), and .trimEnd().

let raw = "   Hello, World!   ";
console.log(raw.trim());       // "Hello, World!"
console.log(raw.trimStart());  // "Hello, World!   "
console.log(raw.trimEnd());    // "   Hello, World!"
Enter fullscreen mode Exit fullscreen mode

8. Splitting Strings πŸ”—

The .split() method splits a string into an array based on a specified delimiter.

let csv = "name,age,city";
let parts = csv.split(",");
console.log(parts); // ["name", "age", "city"]

// Example: splitting sentences
let text = "Hello. How are you? I am fine.";
let sentences = text.split(". ");
console.log(sentences);
// ["Hello", "How are you?", "I am fine."]
Enter fullscreen mode Exit fullscreen mode

9. Joining Strings πŸ”—

Combine an array of strings into one string using .join().

let words = ["JavaScript", "is", "fun"];
console.log(words.join(" ")); // "JavaScript is fun"
Enter fullscreen mode Exit fullscreen mode

10. Padding Strings ⬛

Add characters to the start or end of a string with .padStart() and .padEnd().

let number = "42";
console.log(number.padStart(5, "0")); // "00042"
console.log(number.padEnd(6, "."));  // "42...."
Enter fullscreen mode Exit fullscreen mode

11. Comparing Strings πŸ”€

String comparison in JavaScript is case-sensitive. Use .localeCompare() for advanced comparisons.

let a = "apple";
let b = "banana";
console.log(a.localeCompare(b)); // -1 (a comes before b)
Enter fullscreen mode Exit fullscreen mode

12. Escaping Special Characters 🚧

Use the backslash \ to escape special characters like quotes.

let quote = "She said, \"Hello!\"";
console.log(quote); // She said, "Hello!"
Enter fullscreen mode Exit fullscreen mode

13. Advanced String Manipulation with Regular Expressions πŸ•΅οΈβ€β™‚οΈ

Regular expressions (RegExp) provide powerful ways to search and manipulate strings.

Example: Extracting all numbers:

let data = "Order123, ID456, Code789";
let numbers = data.match(/\d+/g);
console.log(numbers); // ["123", "456", "789"]
Enter fullscreen mode Exit fullscreen mode

Pro Tips for Developers πŸ’‘

  • Performance Matters: When manipulating strings extensively, test the performance of your approach, especially with large data.
  • Immutable Nature: Strings are immutable in JavaScript, meaning every modification creates a new string. Use efficient methods where possible.
  • Localization: When working with multilingual data, consider using Intl APIs for locale-aware operations.

With these techniques, you’re ready to conquer any string-related challenges in JavaScript! Happy coding! ✨

string Article's
30 articles in total
Favicon
Leetcode β€” 2942. Find Words Containing Character
Favicon
Python day-28 Dictionary, Frequency of character using nested loops
Favicon
Python Day-19 csv file,String methods,ASCII,Task
Favicon
Redis Cache - A String story
Favicon
Python Day-22 String Functions logic using loops, Recursion, Tasks
Favicon
Greatest Common Divisor of Strings in Javascript
Favicon
Day 22- String Functions and Recursion
Favicon
Day 21- String Functions
Favicon
Python Day-21 String functions logic using loops
Favicon
Python Day-20 String functions logic using loops,Task
Favicon
Day 20 - String functions
Favicon
Day 19 - CSV file, ASCII, String methods
Favicon
Python Day 6- String Functions,Looping-For,ifelse conditions and Task
Favicon
Python Day 5 - String functions
Favicon
Mastering String Operations in JavaScript πŸš€
Favicon
String Data Structures and Algorithms: Essential Interview Questions
Favicon
Find the First Non-Repeated Character in a String
Favicon
Longest substring without repeating characters
Favicon
Create JS function to remove spaces from giving string. ( Using core js and not in-built trim function.)
Favicon
Write a function that removes duplicate characters from a given string. ( Try to write core JS)
Favicon
Knuth Morris Prat algorithm[Pattern Matching]
Favicon
The JS string replace() method
Favicon
Pergunte ao especialista - Strings
Favicon
Strings
Favicon
C# {String Methods}
Favicon
Extending String for Validation in Dart 3
Favicon
String and Trailing comma, get couple and become, Tuple (): A copy & paste mistake to Error and concept
Favicon
Top 10 String Javascript Interview Coding Question
Favicon
Bash string manipulation
Favicon
C++ ηš„ string η‰©δ»Άεˆ°εΊ•δ½”εΉΎε€‹δ½ε…ƒη΅„οΌŸ

Featured ones: