Examples of JavaScript Strings
All Contributions
Split a string into an array
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Split a String into an Array</title>
</head>
<body>
<script>
var fruitsStr = "Apple, Banana, Mango, Orange, Papaya";
var fruitsArr = fruitsStr.split(", ");
document.write(fruitsArr[0] + "<br>"); // Prints: Apple
document.write(fruitsArr[2] + "<br>"); // Prints: Mango
document.write(fruitsArr[fruitsArr.length - 1]); // Prints: Papaya
document.write("<hr>");
// Loop through all the elements of the fruits array
for(var i in fruitsArr) {
document.write("<p>" + fruitsArr[i] + "</p>");
}
</script>
</body>
</html>
Output :
Apple
Mango
Papaya
Apple
Banana
Mango
Orange
Papaya
Extract a single character from a string using square brackets
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Extract a Single Character from a String</title>
</head>
<body>
<script>
var str = "Hello World!";
document.write(str[0] + "<br>"); // Prints: H
document.write(str[6] + "<br>"); // Prints: W
document.write(str[str.length - 1] + "<br>"); // Prints: !
document.write(str[30]); // Prints: undefined
</script>
</body>
</html>
Output :
H
W
!
undefi ned
Extract a single character from a string
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Extract a Single Character from a String</title>
</head>
<body>
<script>
var str = "Hello World!";
document.write(str.charAt() + "<br>"); // Prints: H
document.write(str.charAt(6) + "<br>"); // Prints: W
document.write(str.charAt(30) + "<br>"); // Prints nothing
document.write(str.charAt(str.length - 1)); // Prints: !
</script>
</body>
</html>
Output :
H
W
!
Join two or more strings
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Join Two or More Strings</title>
</head>
<body>
<script>
var hello = "Hello";
var world = "World";
var greet = hello + " " + world;
document.write(greet + "<br>"); // Prints: Hello World
var wish = "Happy";
wish += " New Year";
document.write(wish); // Prints: Happy New Year
</script>
</body>
</html>
Output :
Hello World
Happy New Year
total contributions (23)
Split a string into an array of characters
Output :
I
N
R
I
N
T
E
R
S
T
E
L
L
A
R