Site icon NexGismo

Mastering in JavaScript String Manipulation: A Comprehensive Guide

Mastering String Manipulation in JavaScript: A Comprehensive Guide
let singleQuoteString = ‘Hello, World!’;
let doubleQuoteString = “Hello, World!”;
let backtickString = `Hello, World! `;  

Basic String Methods

let str = ‘Hello, World!’;
console. log(str. length); // Output: 13
let str = "Hello, World!";  
console.log(str.charAt(0)); // Output: H  
let str = "Hello, World!";  
console.log(str.indexOf('o')); // Output: 4  
let str = "Hello, World!";  
console.log(str.slice(0, 5)); // Output: Hello
let str = "Hello, World!";  
console.log(str.substring(0, 5)); // Output: Hello  
let str = "Hello, World!";  
console.log(str.substr(0, 5)); // Output: Hello  
let str = "Hello, World!";  
let newStr = str.replace('World', 'JavaScript');  
console.log(newStr); // Output: Hello, JavaScript!
let str = "Hello, World!";  
let arr = str.split(', ');  
console.log(arr); // Output: ["Hello", "World!"]  
let str1 = "Hello";  
let str2 = "World";  
let result = str1.concat(', ', str2, '!');  
console.log(result); // Output: Hello, World!  
let str = "Hello, World!";  
console.log(str.toUpperCase()); // Output: HELLO, WORLD!  
console.log(str.toLowerCase()); // Output: hello, world!  
 let str = "   Hello, World!   ";  
console.log(str.trim()); // Output: Hello, World!

Template literals, introduced in ES6, provide an easy way to work with strings. They allow for embedding expressions and multi-line strings, using backticks (`).

let name = "JavaScript";  
let greeting = `Hello, ${name}!`;  
console.log(greeting); // Output: Hello, JavaScript!  
  
let multiLineStr = `This is a string  
that spans multiple  
lines.`;  
console.log(multiLineStr);  
/* Output:  
This is a string  
that spans multiple  
lines.  
*/  

Regular Expressions

let str = "Hello, World!";  
let regex = /World/;  
console.log(str.match(regex)); // Output: ["World"]  
  
let newStr = str.replace(/World/, 'JavaScript');  
console.log(newStr); // Output: Hello, JavaScript!  
function validateEmail(email) {  
    let regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;  
    return regex.test(email);  
}  
  
console.log(validateEmail('test@example.com')); // Output: true  
console.log(validateEmail('invalid-email'));    // Output: false  

Conclusion

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
  2. https://www.w3schools.com/js/js_string_methods.asp

4 Major Problems with JavaScript forEach

Exit mobile version