In JavaScript, you can index, split, and manipulate strings using various built-in methods. Here's an overview of how you can do these operations:
Indexing Strings:JavaScript strings are zero-indexed, meaning each character in a string has an index starting from 0.
let str = "Hello, World!";
console.log(str[0]); // Output: H
console.log(str.charAt(7)); // Output: W
Splitting Strings:
You can split a string into an array of substrings using the split()
method. It takes a delimiter as an argument and divides the string based on that delimiter.
let sentence = "This is a sample sentence";
let words = sentence.split(" "); // Splitting by space
console.log(words); // Output: ["This", "is", "a", "sample", "sentence"]
let csvData = "apple,orange,banana,grape";
let fruits = csvData.split(","); // Splitting by comma
console.log(fruits); // Output: ["apple", "orange", "banana", "grape"]
Manipulating Strings:
JavaScript provides various methods to manipulate strings.
-
Concatenation:
You can concatenate strings using the
+
operator or theconcat()
method.let str1 = "Hello"; let str2 = "World"; let greeting = str1 + " " + str2; // Using the + operator console.log(greeting); // Output: Hello World let fullName = str1.concat(" ", str2); // Using concat() method console.log(fullName); // Output: Hello World
-
Substring and Substr:
substring()
andsubstr()
methods extract parts of a string.let text = "JavaScript"; let slicedText = text.substring(0, 4); // Extracting characters from index 0 to 3 console.log(slicedText); // Output: Java let subStrText = text.substr(4, 6); // Extracting 6 characters starting from index 4 console.log(subStrText); // Output: Script
-
Replacing Text:
The
replace()
method replaces a specified value with another value in a string.let message = "I like oranges."; let newMessage = message.replace("oranges", "apples"); console.log(newMessage); // Output: I like apples.
-
Changing Case:
JavaScript provides
toUpperCase() and toLowerCase()
methods to change the case of a string.let text = "Hello, World!"; console.log(text.toUpperCase()); // Output: HELLO, WORLD! console.log(text.toLowerCase()); // Output: hello, world!
These methods give you flexibility in manipulating, splitting, and accessing different parts of strings in JavaScript.