A string in JavaScript is a sequence of characters. It can be created using single quotes ('
), double quotes ("
), or backticks (`
). Strings are immutable, which means that once a string is created, its value cannot be changed directly. Any operation that seems to modify a string actually creates a new string.
// Using single quotes
let singleQuoted = 'Hello, World!';
// Using double quotes
let doubleQuoted = "Hello, World!";
// Using backticks (template literals)
let templateLiteral = `Hello, World!`;
// Template literals can also include expressions
let name = 'John';
let greeting = `Hello, ${name}!`;
console.log(greeting);
let str = 'JavaScript';
// Accessing the first character
console.log(str[0]);
// Using charAt method
console.log(str.charAt(0));
let str = 'JavaScript';
console.log(str.length);
let str1 = 'Hello';
let str2 = 'World';
// Using + operator
let concatenated = str1 + ' ' + str2;
console.log(concatenated);
// Using concat method
let anotherConcatenated = str1.concat(' ', str2);
console.log(anotherConcatenated);
let str = 'JavaScript is fun';
// Using indexOf
console.log(str.indexOf('is'));
// Using includes
console.log(str.includes('fun'));
let str = 'JavaScript';
// Using slice
console.log(str.slice(0, 4));
// Using substring
console.log(str.substring(0, 4));
let str = 'Hello, World!';
let newStr = str.replace('World', 'JavaScript');
console.log(newStr);
let num = 123;
// Converting number to string
let str = num.toString();
console.log(typeof str);
let str = ' Hello, World! ';
// Using trim
let trimmed = str.trim();
console.log(trimmed);
let str = 'JavaScript';
// Converting to uppercase
console.log(str.toUpperCase());
// Converting to lowercase
console.log(str.toLowerCase());
let url = 'https://example.com?name=John Doe';
// Encoding URL
let encoded = encodeURIComponent(url);
console.log(encoded);
// Decoding URL
let decoded = decodeURIComponent(encoded);
console.log(decoded);
includes
if you only need to check if a substring exists, and indexOf
if you also need the position.JavaScript string manipulation techniques are essential for any JavaScript developer. By understanding the fundamental concepts, usage methods, common practices, and best - practices, you can efficiently handle string data in your applications. Whether you are working on a simple web page or a complex web application, these techniques will help you process and present text data effectively.