String
String
String
String is sequence of characters enclosed withing the pair of double quotation or single quotation
marks.
Ex:
‘abc’,
“xyz”,
“78TT$”
1. Using literal
2. By String Object (Using new keyword)
1. Using Literal
String literal is created by using single quote or double quote
Syntax:
var string_name=’string_value’;
or
var string_name=”string_value”;
example
<html>
<head>
<title>String Example</title>
</head>
<body>
<script>
var string1="samarth";
document.write(string1);
document.write("<br>");
var string2='samarth';
document.write(string2);
</script>
</body>
</html>
syntax:
example
<html>
<head>
<title>String Example</title>
</head>
<body>
<script>
document.write(string1);
document.write("<br>");
document.write(string2);
</script>
</body>
</html>
//output
samarth
Samarth
Manipulating String
String methods
1. charAt(): The charAt() method in JavaScript is used to retrieve the character at a
specified index in a string.
2. charCodeAt(): Returns the Unicode of the character at a specified index in a string.
3. concat(): Combines two or more strings and returns a new string.
4. indexOf(): Returns the index of the first occurrence of a specified value in a string.
5. lastIndexOf(): Returns the index of the last occurrence of a specified value in a string.
6. search(): Searches a string for a specified value and returns the position of the match.
7. match(): Retrieves the matches of a string against a regular expression.
8. replace(): Searches a string for a specified value or a regular expression, and returns a
new string with the value(s) replaced.
9. substr(): Extracts a part of a string, beginning at a specified index and extending for a
given number of characters.
10. substring(): Extracts the characters from a string between two specified indices.
11. slice(): Extracts a section of a string and returns it as a new string.
12. toLowerCase(): Converts a string to lowercase letters.
13. toUpperCase(): Converts a string to uppercase letters.
14. split(): Splits a string into an array of substrings using a specified separator.
15. trim(): Removes whitespace from both ends of a string.
16. toString(): converting number to string
Joining string
concat()
concat() method is used to combines two or more strings and returns a new string.
Syntax:
example
<html>
<head>
<title>Concat Example</title>
<script>
function concatenateStrings() {
let str1 = "Hello, ";
let str2 = "world!";
let result = str1.concat(str2);
document.write(result);
}
</script>
</head>
<body>
<script>
concatenateStrings();
</script>
</body>
</html>
//output
Hello, world!
<html>
<head>
<title>charAt() Example</title>
<script>
function displayCharacter() {
let str = "Hello, world!";
let char = str.charAt(7);
document.write("The character at index 7 is: " + char);
}
</script>
</head>
<body>
<script>
displayCharacter();
</script>
</body>
</html>
//output
The character at index 7 is: w
Syntax:
string.indexOf(searchValue, start)
string: The string in which to search.
searchValue: The value to search for within the string.
start (optional): The position in the string at which to start the search. Default is 0.
<html>
<head>
<title>indexOf() Example</title>
<script>
function findIndexOf() {
let str = "Hello, world!";
let index = str.indexOf("o");
document.write("The first occurrence of 'o' is at index: " + index);
}
</script>
</head>
<body>
<script>
findIndexOf();
</script>
</body>
</html>
//Output
The first occurrence of 'o' is at index: 4
lastIndexOf()
The lastIndexOf() method returns the index of the last occurrence of a specified value in a
string. If the value is not found, it returns -1.
Syntax:
string.lastIndexOf(searchValue, start);
string: The string in which to search.
searchValue: The value to search for within the string.
start (optional): The position in the string at which to start the search backward. Default is
str.length - 1.
Example
<html>
<head>
<title>lastIndexOf() Example</title>
<script>
function findLastIndexOf() {
let str = "Hello, world!";
let index = str.lastIndexOf("o");
document.write("The last occurrence of 'o' is at index: " + index);
}
</script>
</head>
<body>
<script>
findLastIndexOf();
</script>
</body>
</html>
//output
The last occurrence of 'o' is at index: 8
Dividing Text
The split() method divides a string into an array of substrings based on a specified separator
and returns the new array.
Syntax:
string.split(separator, limit)
string: The string to be split.
separator: Specifies the character(s) to use for splitting the string. If omitted, the entire
string is returned as a single element array.
limit (optional): An integer that specifies the number of splits to be found.
Example
<html>
<head>
<title>split() Example</title>
<script>
function splitString() {
let str = "Welcome to JavaScript.";
let words = str.split(" ");
document.write("<b>words are: </b>" + words.join(", "));
}
</script>
</head>
<body>
<script>
splitString();
</script>
</body>
</html>
//output
words are: Welcome, to, JavaScript.
1. toUpperCase()
Syntax:
string.toUpperCase()
<html>
<head>
<title>toUpperCase() Example</title>
<script>
function convertToUpperCase() {
let str = "Hello, world!";
let upperStr = str.toUpperCase();
document.write("The uppercase string is: " + upperStr);
}
</script>
</head>
<body>
<script>
convertToUpperCase();
</script>
</body>
</html>
//output
The uppercase string is: HELLO, WORLD!
toLowerCase()
The toLowerCase() method converts all the characters in a string to lowercase letters.
Syntax:
string.toLowerCase()
Example
<html>
<head>
<title>toLowerCase() Example</title>
<script>
function convertToLowerCase() {
let str = "Hello, WORLD!";
let lowerStr = str.toLowerCase();
document.write("The lowercase string is: " + lowerStr);
}
</script>
</head>
<body>
<script>
convertToLowerCase();
</script>
</body>
</html>
Output
Copying Substring
1. substring()
The substring() method in JavaScript is used to extract a part of a string and
return it as a new string, without modifying the original string.
syntax
string.substring(startIndex, endIndex);
endIndex is optional, if it is not given the fetch substring from start index to
end of the string
<html>
<head>
</head>
<body>
<script>
</script>
</body>
</html>
Output
Hello
World
World!
World
World!
2. slice()
The slice() method in JavaScript is used to extract a part of a string and return it
as a new string, without modifying the original string.
It allows for both positive and negative indices to specify the start and end of
the slice.
Syntax:
string.slice(beginIndex, endIndex);
endIndex is optional, if it is not given the fetch substring from start index to end of the
string
beginIndex: The index at which to start the slice (inclusive). If negative, it is counted from
the end of the string.
endIndex: The index at which to end the slice (exclusive). If omitted or greater than the
string length, it slices to the end of the string. Negative values are also counted from the end.
<html>
<head>
</head>
<body>
<script>
// Extract "Hello"
// Extract "World"
</script>
</body>
</html>
Output
Hello: Hello
World: World
World!
negativeIndices
World
World!
substring() slice()
If startIndex is greater than endIndex, the If startIndex is greater than endIndex, the
method swaps them. method returns an empty string.
let text = "Hello, world!"; let text = "Hello, world!";
console.log(text.substring(0, 5)); // "Hello" console.log(text.slice(0, 5)); // "Hello"
console.log(text.substring(5, 0)); // "Hello" console.log(text.slice(5, 0)); // ""
Negative indices are treated as 0. Allows negative indices to count from the
end of the string.
let text = "Hello, world!"; let text = "Hello, world!";
console.log(text.slice(5, -3)); // ", wor" console.log(text.slice(-6)); // "world!"
substr():
The substr() method in JavaScript is used to extract a part of a string and return
it as a new string, without modifying the original string.
Syntax:
string.substr(startIndex, length);
startIndex: The index at which to begin extraction. If negative, it counts from the end of the
string.
length (optional): The number of characters to extract. If omitted, extracts to the end of the
string.
Example
<html>
<head>
</head>
<body>
<script>
</script>
</body>
</html>
//Output
Hello
World
World!
World
World!
1.parseInt()
Syntax:
parseInt(string, radix)
string: The string to be parsed. If the string does not start with a numeric value,
parseInt() will return NaN.
radix (optional): represents the base of the numeral system to be used. For
example, a radix of 10 represents the decimal system, 16 represents
hexadecimal, etc.
<html>
<head>
<title>parseInt Examples</title>
</head>
<body>
<script>
</script>
</body>
</html>
Output
Decimal (42): 42
Number()
Number(value)
It can convert strings, booleans, and other types to numbers, and it returns
null converts to 0.
undefined converts to NaN.
<html>
<head>
<title>Number() Examples</title>
</head>
<body>
<script>
let num1 = Number("42");
let num2 = Number(true);
let num3 = Number(false);
let num4 = Number(" 123 ");
let num5 = Number("");
let num6 = Number("abc123");
let num7 = Number(null);
let num8 = Number(undefined);
toString()
The toString() method in JavaScript converts a number, object, or other data types to a
string.
Syntax:
value.toString([radix])
// Boolean to string
let bool = true;
let boolStr = bool.toString();
document.write("Boolean to string: " + boolStr + "<br>");
// Object to string
let obj = {name: "Alice", age: 30};
let objStr = obj.toString();
document.write("Object to string: " + objStr + "<br>");
// Array to string
let arr = [1, 2, 3];
let arrStr = arr.toString();
document.write("Array to string: " + arrStr + "<br>");
</script>
</body>
</html>
Output
Number to string: 42
Number to binary string: 101010
Boolean to string: true
Object to string: [object Object]
Array to string: 1,2,3
fromCharCode()
The String.fromCharCode() method in JavaScript creates a string from one or more
Unicode values.
Syntax:
String.fromCharCode(num1, num2, ..., numN);
Example
<html>
<head>
<title>String.fromCharCode() Example</title>
</head>
<body>
<script>
// Single Unicode value
let char1 = String.fromCharCode(65);
document.write("Char1: " + char1 + "<br>");
</body>
</html>
Output:
Char1: A
Char2: Hello
Char3: Code Queen