JavaScript String
A string in JavaScript is a sequence of characters, enclosed within quotes. In JavaScript, strings can be of two types: primitive and object.
Syntax
The syntax for creating a string in JavaScript is as follows:
var str = "Hello, world!";
The above syntax declares a string variable str
with the value "Hello, world!".
Example
Let's take an example to demonstrate the usage of strings in JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript String Example</title>
</head>
<body>
<!-- Placeholder for displaying the output -->
<p id="output"></p>
<script>
// Define variables
var name = "John Doe";
var greeting = "Hello";
var message = greeting + " " + name;
// Display the message in the HTML document
document.getElementById("output").innerHTML = "Output: " + message;
</script>
</body>
</html>
In the above example, we have concatenated two strings greeting
and name
using the +
operator and assigned the result to the message
variable. The console.log()
method is used to print the output, which will be "Hello John Doe".
Output
The output of the above example will be:
Hello John Doe