Creating a String Variable
var keyword followed by the variable name and an assignment operator (
=) to assign a value to the variable. Here’s an example:
var message = "Hello, World!";
In the above example, we have created a string variable named
message and assigned it the value “Hello, World!”. The value is enclosed within double quotes as it is considered good practice.
+ operator. This allows you to combine multiple strings into one. Here’s an example:
var firstName = "John"; var lastName = "Doe"; var fullName = firstName + " " + lastName;
The above code will concatenate the values of
firstName, a space character (enclosed within double quotes), and
lastName. The final result will be stored in the
Finding the Length of a String
You can determine the length of a string using its
.length property. The length property returns the number of characters in a string (including whitespace). Here’s an example:
var greeting = "Hello, World!"; var length = greeting.length;
In the above code, the
length variable will store the value
13, as the string “Hello, World!” consists of 13 characters.
Accessing Individual Characters
0. Here’s an example:
var text = "Hello"; var firstCharacter = text; // 'H'
In this example, the variable
firstCharacter will store the value
'H', which is the first character of the string
The String Object Methods
- .toUpperCase(): Converts a string to uppercase.
- .toLowerCase(): Converts a string to lowercase.indexOf(): Returns the index of a specified substring within a string.substring(): Extracts a portion of a string based on specified start and end indices.replace(): Replaces occurrences of a specified substring with another substring.
Strings are fundamental to web development and programming in general. Understanding how to work with strings effectively will greatly enhance your ability to develop robust and dynamic applications.