📘 Lesson  ·  Lesson 10

String Methods

String Methods

What String Methods Are

let name = "  Aman Kumar  ";
console.log(name.trim());        // "Aman Kumar"
console.log(name);               // "  Aman Kumar  "  ← UNCHANGED!
Methods are built-in functions you call ON a value, using a dot: value.method(). Strings come with dozens of them for searching, changing case, extracting pieces, and more. There's one crucial rule to internalise: string methods NEVER change the original string — they return a NEW string. Strings are "immutable" in JavaScript. So name.trim() gives you back a trimmed copy, but name itself is untouched. If you want to keep the result, you must store it: name = name.trim(). Forgetting this is a very common beginner mistake.

Changing Case and Trimming

let text = "  Hello World  ";

text.toUpperCase();    // "  HELLO WORLD  "
text.toLowerCase();    // "  hello world  "
text.trim();           // "Hello World"   (removes spaces at both ends)
toUpperCase() and toLowerCase() convert a string's case — invaluable for comparing user input case-insensitively (comparing input.toLowerCase() against "yes" catches "Yes", "YES", and "yes" all at once). trim() removes whitespace from both ends of a string — absolutely essential when handling form input, because users constantly type accidental leading or trailing spaces. Almost every real form-handling script starts by trimming the input. These three simple methods solve a surprising number of real problems.
let email = "aman@gmail.com";

email.includes("@");        // true   — does it contain "@"?
email.indexOf("@");         // 4      — at what position? (-1 if not found)
email.startsWith("aman");   // true
email.endsWith(".com");     // true
includes() is the clearest way to ask "does this string contain that?" — it returns simply true or false. indexOf() answers "where is it?" by returning the position (remember: 0-based), or -1 if the text isn't found at all. That -1 is a classic convention worth remembering. startsWith() and endsWith() check the beginning and end. Together these power validation and search features — checking an email has an "@", filtering a list by typed text, verifying a file ends with ".jpg".

Extracting Parts of a String

let text = "JavaScript";

text.slice(0, 4);      // "Java"   — from index 0 up to (not including) 4
text.slice(4);         // "Script" — from index 4 to the end
text.slice(-6);        // "Script" — last 6 characters (negative counts back)

text.charAt(0);        // "J"      — a single character
text.substring(0, 4);  // "Java"   — similar to slice
slice(start, end) is the main tool for cutting out part of a string. Two things to note carefully: the start index is INCLUDED but the end index is EXCLUDED — so slice(0, 4) gives characters 0, 1, 2, 3 (that's "Java"). Leave out the end to go all the way to the finish. And a useful trick: NEGATIVE numbers count from the end, so slice(-6) gives the last 6 characters. substring() is very similar (but doesn't accept negatives). Master slice — it works on arrays too, with exactly the same rules.

Replacing and Splitting

let text = "I like cats";
text.replace("cats", "dogs");        // "I like dogs" (first match only)
text.replaceAll("a", "@");           // replaces EVERY match

// split() turns a string into an ARRAY:
let csv = "Aman,Priya,Ravi";
csv.split(",");                      // ["Aman", "Priya", "Ravi"]
"Hello".split("");                   // ["H","e","l","l","o"]

// join() does the reverse (array → string):
["Aman","Priya"].join(" & ");        // "Aman & Priya"
replace() swaps text for other text — but note it only replaces the FIRST occurrence; use replaceAll() to change every one. split() is a real workhorse: it breaks a string into an ARRAY, cutting at whatever separator you give it. Splitting on a comma turns CSV data into a usable list; splitting on " " gives you words; splitting on "" gives every character. Its opposite, join(), glues an array back into a string. This split/join pair is one of the most practical combos in JavaScript for processing text.

Exam Corner

Q: Do string methods change the original string? No — strings are immutable; methods return a new string.

Q: Which method removes spaces from both ends? trim()

Q: What does indexOf return if the text isn't found? -1

Q: What does slice(0, 4) return from "JavaScript"? "Java" — the end index is excluded.

Q: What does split(",") do? Breaks a string into an array, cutting at each comma.

String Methods क्या हैं

let name = "  Aman Kumar  ";
console.log(name.trim());        // "Aman Kumar"
console.log(name);               // "  Aman Kumar  "  ← ANBADLA!
Methods built-in functions हैं जिन्हें आप किसी value PAR call करते हैं, dot से: value.method(). Strings के साथ दर्जनों आते हैं खोजने, case बदलने, टुकड़े निकालने, और ज़्यादा के लिए. एक अहम rule आत्मसात कीजिए: string methods मूल string को KABHI नहीं बदलते — वे NAYI string लौटाते हैं. JavaScript में strings "immutable" हैं. तो name.trim() आपको trimmed copy वापस देता है, पर name खुद अछूता है. नतीजा रखना है तो store करना होगा: name = name.trim(). यह भूलना बहुत common beginner गलती है.

Case बदलना और Trimming

let text = "  Hello World  ";

text.toUpperCase();    // "  HELLO WORLD  "
text.toLowerCase();    // "  hello world  "
text.trim();           // "Hello World"   (dono siron se spaces hatata)
toUpperCase() और toLowerCase() string का case बदलते हैं — user input की case-insensitive तुलना के लिए अमूल्य (input.toLowerCase() की "yes" से तुलना "Yes", "YES", और "yes" सब एक साथ पकड़ती है). trim() string के DONO सिरों से whitespace हटाता है — form input संभालते समय बिल्कुल ज़रूरी, क्योंकि users लगातार गलती से आगे-पीछे spaces type करते हैं. लगभग हर असली form-handling script input trim करके शुरू होती है. ये तीन सरल methods आश्चर्यजनक संख्या में असली समस्याएं हल करते हैं.

Strings के अंदर खोजना

let email = "aman@gmail.com";

email.includes("@");        // true   — kya isme "@" hai?
email.indexOf("@");         // 4      — kis position par? (na mile to -1)
email.startsWith("aman");   // true
email.endsWith(".com");     // true
includes() "क्या इस string में वह है?" पूछने का सबसे साफ तरीका है — यह बस true या false लौटाता है. indexOf() "यह कहां है?" का जवाब position लौटाकर देता है (याद रखिए: 0-based), या -1 अगर text बिल्कुल न मिले. वह -1 याद रखने लायक classic convention है. startsWith() और endsWith() शुरुआत और अंत जांचते हैं. साथ में ये validation और search features चलाते हैं — email में "@" है जांचना, typed text से list filter करना, file ".jpg" पर खत्म होती है सत्यापित करना.

String के हिस्से निकालना

let text = "JavaScript";

text.slice(0, 4);      // "Java"   — index 0 se 4 tak (4 shamil nahi)
text.slice(4);         // "Script" — index 4 se ant tak
text.slice(-6);        // "Script" — aakhri 6 characters (negative peeche se ginta)

text.charAt(0);        // "J"      — ek character
text.substring(0, 4);  // "Java"   — slice jaisa
slice(start, end) string का हिस्सा काटने का मुख्य tool है. दो बातें ध्यान से: start index SHAMIL है पर end index BAHAR है — तो slice(0, 4) characters 0, 1, 2, 3 देता है (यानी "Java"). End छोड़ दीजिए तो बिल्कुल अंत तक जाता है. और उपयोगी trick: NEGATIVE numbers अंत से गिनते हैं, तो slice(-6) आखिरी 6 characters देता है. substring() बहुत समान है (पर negatives स्वीकार नहीं करता). slice master कीजिए — यह arrays पर भी ठीक इन्हीं rules से चलता है.

Replace और Split

let text = "I like cats";
text.replace("cats", "dogs");        // "I like dogs" (sirf pehla match)
text.replaceAll("a", "@");           // HAR match badalta hai

// split() string ko ARRAY me badalta hai:
let csv = "Aman,Priya,Ravi";
csv.split(",");                      // ["Aman", "Priya", "Ravi"]
"Hello".split("");                   // ["H","e","l","l","o"]

// join() ulta karta hai (array → string):
["Aman","Priya"].join(" & ");        // "Aman & Priya"
replace() text को दूसरे text से बदलता है — पर ध्यान यह सिर्फ PEHLA occurrence बदलता है; हर एक बदलने को replaceAll() use कीजिए. split() असली मेहनती है: यह string को ARRAY में तोड़ता है, जो भी separator आप दें उस पर काटते. Comma पर split करना CSV data को इस्तेमाल लायक list बनाता है; " " पर split करना शब्द देता है; "" पर हर character. इसका उल्टा, join(), array को वापस string में चिपकाता है. यह split/join जोड़ी text process करने के लिए JavaScript के सबसे व्यावहारिक combos में से एक है.

Exam Corner

Q: क्या string methods मूल string बदलते हैं? नहीं — strings immutable हैं; methods नई string लौटाते हैं.

Q: कौन-सा method दोनों सिरों से spaces हटाता है? trim()

Q: Text न मिलने पर indexOf क्या लौटाता है? -1

Q: "JavaScript" से slice(0, 4) क्या लौटाता है? "Java" — end index बाहर है.

Q: split(",") क्या करता है? String को array में तोड़ता है, हर comma पर काटते.
← Back to JavaScript Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

इस पेज का code यहाँ तैयार है — बदलिए और तुरंत नतीजा देखिए. कुछ install किए बिना.
👁 Live Preview
सब कुछ आपके browser में ही चलता है — कोई server, कोई signup नहीं. JavaScript का console.log देखने के लिए F12 दबाइए.