# String in JavaScript — Complete Guide with Examples & Practice Problems

Working with strings is one of the most common tasks in JavaScript. Whether you're manipulating text, validating input, or formatting data — strings are everywhere!

In this blog, we’ll explore **all important string methods**, explain them with **easy examples**, and finally give you **interview-level practice problems** to boost your skills.

---

# 🔹 **1\. Length of a String**

To find the total number of characters in a string:

```apache
let firstName = "Vaishali";
console.log(firstName.length);
```

---

# 🔹 **2\. Accessing Characters from a String**

JavaScript allows accessing characters using `charAt()` or bracket notation:

```apache
console.log(firstName.charAt(2)); // i
console.log(firstName[2]);        // i
console.log(firstName.charCodeAt(2)); // ASCII Code
```

---

# 🔹 **3\. Check Presence of a Character**

Use `includes`, `indexOf`, and `lastIndexOf`:

```apache
console.log(firstName.includes("r")); // false
console.log(firstName.indexOf("i"));  // 2
console.log(firstName.lastIndexOf("i")); // 7
```

---

# 🔹 **4\. Compare Two Strings**

`localeCompare()` compares two strings lexicographically:

```apache
let anotherName = "Vishal";
console.log(firstName.localeCompare(anotherName)); // -1
```

---

# 🔹 **5\. Replace Substring in a String**

```apache
const str = "Vishal is Best Frontend Developer. Vishal is Best Developer.";

console.log(str.replace("Vishal", "Sujit"));  
console.log(str.replaceAll("Vishal", "Sujit"));
```

---

# 🔹 **6\. Extract Substring**

```apache
console.log(str.substring(6, 30));
console.log(str.slice(-10, -1));
```

---

# 🔹 **7\. Split and Join Strings**

```apache
console.log(str.split("")); // Split into characters

const subString = str.split(" ");
console.log(subString.join(" "));
```

---

# 🔹 **8\. Check String Start & End**

```apache
console.log(str.startsWith("Vishal"));    // true
console.log(str.endsWith("Developer"));   // true
```

---

# 🔹 **9\. Trim & Case Conversion**

```apache
const trimStr = str.trim();
const trimStrStart = str.trimStart();
const trimStrEnd = str.trimEnd();

console.log(trimStr, trimStr.length);
console.log(str.toLowerCase());
console.log(str.toUpperCase());
```

---

# 🔹 **10\. Convert Number or Object to String**

```apache
const num = 123;
console.log(num.toString());

const obj = { name: "Vishal", course: "DSA with Vishal" };
console.log(JSON.stringify(obj));
```

---

# 🔹 **11\. Concatenate Strings**

```apache
const lastName = "Rajput";

console.log(firstName + lastName);
console.log(`${firstName} ${lastName} is a Best Developer`);
console.log(firstName.concat(lastName, " is a", " Best"));
```

---

# 🧠 **Practice Questions (Interview Level)**

These are common string problems asked in companies like TCS, Infosys, Amazon, Google, Wipro, etc.

1. **Find the Index of the First Occurrence in a String**
    
2. **Reverse String**
    
3. **Valid Anagram**
    
4. **Longest Common Prefix**
    
5. **Merge Strings Alternately**
    
6. **Length of Last Word**
    
7. **Valid Palindrome**
    
8. **String Compression**
    
9. **Reverse Words in a String**
    
10. **Reverse Vowels of a String**
    
11. **Rotate String**
    

# ✅ **1\. Find the Index of the First Occurrence in a String**

👉 Return the first index where `needle` appears in `haystack`.

### ✔ Solution

```apache
function strStr(haystack, needle) {
    return haystack.indexOf(needle);
}

console.log(strStr("hello", "ll")); // 2
console.log(strStr("abc", "d"));    // -1
```

---

# ✅ **2\. Reverse String**

👉 Reverse the characters in a string.

### ✔ Solution

```apache
function reverseString(str) {
    return str.split("").reverse().join("");
}

console.log(reverseString("hello")); // "olleh"
```

---

# ✅ **3\. Valid Anagram**

👉 Two strings are anagrams if both contain the same characters in the same frequency.

### ✔ Solution

```apache
function isAnagram(s, t) {
    if (s.length !== t.length) return false;

    return s.split("").sort().join("") === t.split("").sort().join("");
}

console.log(isAnagram("anagram", "nagaram")); // true
console.log(isAnagram("rat", "car")); // false
```

---

# ✅ **4\. Longest Common Prefix**

👉 Find the longest prefix shared by all strings.

### ✔ Solution

```apache
function longestCommonPrefix(strs) {
    strs.sort();
    let first = strs[0];
    let last = strs[strs.length - 1];
    let i = 0;

    while (i < first.length && first[i] === last[i]) {
        i++;
    }
    return first.slice(0, i);
}

console.log(longestCommonPrefix(["flower", "flow", "flight"])); // "fl"
```

---

# ✅ **5\. Merge Strings Alternately**

👉 Merge characters one-by-one from two strings.

### ✔ Solution

```apache
function mergeAlternately(a, b) {
    let result = "";
    let i = 0;

    while (i < a.length || i < b.length) {
        if (i < a.length) result += a[i];
        if (i < b.length) result += b[i];
        i++;
    }
    return result;
}

console.log(mergeAlternately("abc", "pqr")); // "apbqcr"
```

---

# ✅ **6\. Length of Last Word**

👉 Return the length of the last word in a string.

### ✔ Solution

```apache
function lengthOfLastWord(s) {
    return s.trim().split(" ").pop().length;
}

console.log(lengthOfLastWord("Hello World")); // 5
```

---

# ✅ **7\. Valid Palindrome**

👉 Check if string is same when reversed (ignore symbols & spaces).

### ✔ Solution

```apache
function isPalindrome(s) {
    s = s.toLowerCase().replace(/[^a-z0-9]/g, '');
    return s === s.split("").reverse().join("");
}

console.log(isPalindrome("A man, a plan, a canal: Panama")); // true
```

---

# ✅ **8\. String Compression**

👉 Compress repeated characters like:  
`aabbccc` → `a2b2c3`

### ✔ Solution

```apache
function compress(chars) {
    let i = 0, ans = "";

    while (i < chars.length) {
        let char = chars[i];
        let count = 0;

        while (i < chars.length && chars[i] === char) {
            count++;
            i++;
        }

        ans += char + (count > 1 ? count : "");
    }
    return ans;
}

console.log(compress("aabbccc")); // a2b2c3
```

---

# ✅ **9\. Reverse Words in a String**

👉 Example:  
`" hello world "` → `"world hello"`

### ✔ Solution

```apache
function reverseWords(s) {
    return s.trim().split(/\s+/).reverse().join(" ");
}

console.log(reverseWords("  hello world  ")); // "world hello"
```

---

# ✅ **10\. Reverse Vowels of a String**

👉 Only reverse vowels (a, e, i, o, u).

### ✔ Solution

```apache
function reverseVowels(s) {
    let vowels = "aeiouAEIOU";
    let arr = s.split("");
    let left = 0, right = arr.length - 1;

    while (left < right) {
        if (!vowels.includes(arr[left])) left++;
        else if (!vowels.includes(arr[right])) right--;
        else {
            [arr[left], arr[right]] = [arr[right], arr[left]];
            left++;
            right--;
        }
    }
    return arr.join("");
}

console.log(reverseVowels("hello")); // "holle"
```

---

# ✅ **11\. Rotate String**

👉 Check if string can be rotated to become another string.

Example:  
`"abcde"` rotated → `"cdeab"`

### ✔ Solution

```apache
function rotateString(s, goal) {
    return s.length === goal.length && (s + s).includes(goal);
}

console.log(rotateString("abcde", "cdeab")); // true
```

---

# 🎯 Final Thoughts

JavaScript provides a rich set of string manipulation methods that help developers handle text efficiently. Mastering these methods not only sharpens your coding skills but also prepares you for interviews and real-world development tasks.
