In JavaScript, a string is a sequence of characters enclosed within single quotes (‘…’) or double quotes (“…”). Strings are used to represent text data in JavaScript and are immutable, which means that once a string is created, it cannot be modified.
For example, the following are valid string literals in JavaScript:
let str1 = 'Hello, World!'; // using single quotes
let str2 = "JavaScript is awesome!"; // using double quotes
Here are some common string manipulation methods:
Method | Description | Example |
---|---|---|
charAt(index) | Returns the character at the specified index in a string. | "hello".charAt(0) // "h" |
concat(str1, str2, ...) | Combines two or more strings and returns a new string. | "hello".concat(" world") // "hello world" |
indexOf(substring) | Returns the index of the first occurrence of a substring within a string, or -1 if the substring is not found. | "hello world".indexOf("o") // 4 |
lastIndexOf(substring) | Returns the index of the last occurrence of a substring within a string, or -1 if the substring is not found. | "hello world".lastIndexOf("o") // 7 |
replace(searchValue, replaceValue) | Searches for a searchValue in a string and replaces it with a replaceValue. | "hello world".replace("world", "there") // "hello there" |
substring(startIndex, endIndex) | Returns the substring between the startIndex and endIndex (exclusive) of a string. | "hello world".substring(0, 5) // "hello" |
toLowerCase() | Returns a new string with all characters in lower case. | "HELLO WORLD".toLowerCase() // "hello world" |
toUpperCase() | Returns a new string with all characters in upper case. | "hello world".toUpperCase() // "HELLO WORLD" |
JavaScript string example
A simple example code demonstrates some of the string methods in action:
<!DOCTYPE html>
<html>
<head>
<script>
let str = "JavaScript is Awesome!";
console.log(str.charAt(0));
console.log(str.concat(" And Fun"));
console.log(str.indexOf("Awesome"));
console.log(str.replace("Awesome", "Amazing"));
console.log(str.substring(0, 10));
console.log(str.toLowerCase());
console.log(str.toUpperCase());
</script>
</head>
<body>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this JS basic topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version