-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path40. Remove spaces from string .js
More file actions
74 lines (63 loc) · 2.06 KB
/
40. Remove spaces from string .js
File metadata and controls
74 lines (63 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// remove spaces from string :
// --------------------------------------------------------------------------------------------------------------::
// Using replace() with regex (removes all spaces)
const removeSpaces1 = (str) => {
if (!str) return "";
return str.replace(/\s/g, "");
};
console.log("removeSpaces1('Hello World'): ", removeSpaces1('Hello World'));
console.log("removeSpaces1(' Hello World '): ", removeSpaces1(' Hello World '));
/*
Explanation:
====================
const removeSpaces1 = (str) => {
if (!str) return "";
return str.replace(/\s/g, "");
};
HOW IT WORKS:
- Uses replace() method with regex /\s/g
- \s matches any whitespace character (space, tab, newline, etc.)
- g flag for global replacement (all occurrences)
- Replaces all whitespace with empty string
EXAMPLE: "Hello World" → "HelloWorld"
REMOVES: spaces, tabs, newlines, carriage returns
*/
// Manual loop approach (no built-in methods)
// ------------------------------------------------------------------------------------
const removeSpaces2 = (str) => {
if (!str) return "";
let result = "";
for (let i = 0; i < str.length; i++) {
if (str[i] !== " ") {
result += str[i];
}
}
return result;
};
console.log("removeSpaces2('Hello World'): ", removeSpaces2('Hello World'));
console.log("removeSpaces2('JavaScript Programming'): ", removeSpaces2('JavaScript Programming'));
/*
Explanation:
====================
const removeSpaces2 = (str) => {
if (!str) return "";
let result = "";
for (let i = 0; i < str.length; i++) {
if (str[i] !== " ") {
result += str[i];
}
}
return result;
};
HOW IT WORKS:
- Loops through each character manually
- Checks if character is not a space
- Concatenates non-space characters to result string
- Only removes regular spaces (ASCII 32), not tabs/newlines
STEP-BY-STEP EXAMPLE: "Hi There"
i=0: 'H' (not space) → result = "H"
i=1: 'i' (not space) → result = "Hi"
i=2: ' ' (is space) → skip
i=3: 'T' (not space) → result = "HiT"
...Final result: "HiThere"
*/