The data type that contains text is called a JavaScript string. Strings help you manipulate and display text on JavaScript programs. In this tutorial, you'll get the idea on how to write them easily.
You will also learn about string properties and methods, using JavaScript escape quotes or backslashes (if needed) and creating JavaScript multiline strings.
Contents
JavaScript Strings: Main Tips
- Strings are a data type used to store and manipulate text.
- JavaScript string definition requires the data to be written in quotes (single or double).
- Even though it's possible, JavaScript strings should not be created as objects. Doing so may complicate the code and slow down its execution.
Strings by Definition
JavaScript string is a data type used to store textual data. Any text written as a function's property value inside quotes is considered to be a string.
JavaScript accepts both single and double quotes. It does not make any difference to execution, speed, or the function at all. Check the example of JavaScript strings in both single and double quotes below:
Quotes may be used inside strings as well, but they have to be different from the quotes that surround the string. For example, if you use double quotes around the string, you must use single quotes inside, and vice versa:
var name1 = "value";
var name2 = "value 'quoted'";
var name3 = 'value "quoted"';
Due to strings having to be written within quotes, the code below will be misinterpreted by JavaScript:
var b = "Our team is called "BitDegree"."
The string shown above is going to be chopped into "Our team is called "
. One of the ways of avoiding this problem is using the \
escape character. The backslash turns special characters into string characters, just like in the code example below:
var a = 'It\'s alright.';
var b = "Our team is called \"BitDegree\"."
In this example below, we are using the \'
to add a '
to a string:
var exampleVar = "I\'m going to get some snacks";
document.getElementById("eg1").innerHTML = exampleVar;
Remember that \'
will become '
and the \"
will be included in the string as "
. In this example, we are using \"
:
var exampleVar = "To quote Confucius, \"It does not matter how slowly you go as long as you do not stop.\"";
document.getElementById("eg1").innerHTML = exampleVar;
Here is a list of special characters you can add using the backslash:
Code | Character |
---|---|
\' | JavaScript escape quotes (single) |
\" | JavaScript escape quotes (double) |
\\ | JavaScript escape backslash |
\n | JavaScript escape break line |
\r | JavaScript escape return carriage |
\t | JavaScript escape tab |
\b | JavaScript escape backspace |
\f | JavaScript escape form feed |
Breaking Long Strings
For you to easily find the string length JavaScript has a property called length
. It returns the number of characters used in a string:
For purposes of readability, programmers tend to avoid lines longer than 80 characters, as it is inconvenient to scroll sideways repeatedly:
document.getElementById("eighty").innerHTML ="Would you believe it if I said this text consists of exactly eighty characters?!";
In case a statement cannot fit into a single line (or the 80 character limit), you should try to break it into a separate line, thus creating a JavaScript multiline string. It is possible to break up a line inside of a string with a single backslash, as in the example below:
Note: keep in mind that this method is not an ECMAScript standard, so it is not supported by all browsers (some don't allow spaces before the backslash).
Code lines, however, cannot be broken up using a backslash. This only works for text (string data):
A safer, but also a slower way to create a JavaScript multiline string is using string addition:
- Easy to use with a learn-by-doing approach
- Offers quality content
- Gamified in-browser coding experience
- The price matches the quality
- Suitable for learners ranging from beginner to advanced
- Free certificates of completion
- Focused on data science skills
- Flexible learning timetable
- Simplistic design (no unnecessary information)
- High-quality courses (even the free ones)
- Variety of features
- Nanodegree programs
- Suitable for enterprises
- Paid Certificates of completion
- A wide range of learning programs
- University-level courses
- Easy to navigate
- Verified certificates
- Free learning track available
- University-level courses
- Suitable for enterprises
- Verified certificates of completion
Strings as Objects
Normally, strings in JavaScript are only primitive values, created from literals like var name = "value"
. However, by using the keyword new
, they can also be declared as objects - var name = new String("value")
:
var a = "Joe"; // typeof a returns string
var b = new String("Joe"); // typeof b returns object
When you use the ==
comparison operator, these two JavaScript strings look equal:
var a = "Joe";Â Â Â Â Â Â Â Â Â Â Â Â Â
var b = new String("Joe"); // (a == b) is true since the values of a and b are equal
Now, when you use the ===
operator, those same strings are not equal, since the ===
operator expects both the value and the type to be equal:
var a = "Joe";Â Â Â Â Â Â Â Â Â Â Â Â Â
var b = new String("Joe"); // (a === b) is false because the object types of a and b are different
Keep in mind that two objects cannot be compared at all:
var a = new String("Joe");Â Â Â Â Â Â Â Â Â Â Â Â Â
var b = new String("Joe");
// (a == b) is false since since objects cannot be compared
// (a == a) is true since its a single object being compared to itself
Properties and Methods
Primitive values like "word"
cannot have methods or properties (they are not objects). Still, in JavaScript, properties and methods can also be used with primitive values, since JavaScript treats them as objects while executing properties and methods.
Have a look at the table with a list of possible properties of JavaScript strings:
Property | Description |
---|---|
constructor | Return the function that created the string object prototype |
length | Return JavaScript string length |
prototype | Allow adding methods and properties to an object |
Let's examine the methods table below, too:
Method | Description |
---|---|
charAt() | Return character at a specified index (position) |
charCodeAt() | Return the unicode of a character at a specified index |
concat() | Join single or multiple strings and return a copy of joined strings |
fromCharCode() | Convert unicode values to characters |
indexOf() | Return the position of the first found occurrence of the defined text in a string |
lastIndexOf() | Return the position of the last found occurrence of the specified text in a string |
localeCompare() | Compare two strings in current locale |
match() | Search string for a match against the regular expression, and return matches |
replace() | Search string for value and return new string with the value replaced |
search() | Search string for value and return the position of the match |
slice() | Extract part of a string and return a new string |
split() | Split string into the array of substrings |
substr() | Extract part of the string starting at a specified index through a specified number of characters |
substring() | Extract part of the string between two specified positions |
toLocaleLowerCase() | Convert string to lowercase letters, according to host's locale |
toLocaleUpperCase() | Convert string to uppercase letters, according to host's locale |
toLowerCase() | Convert string to lowercase letters |
toString() | Return the value of the string object |
toUpperCase() | Convert string to uppercase letters |
trim() | Remove whitespace from both ends of the string |
valueOf() | Return primitive value of string object |
JavaScript Strings: Summary
- JavaScript string is a type of data which stores textual data.
- JavaScript strings can manipulate data in the JavaScript environment.
- JavaScript escape quotes, slashes, line breaks, etc. can be included using backslash (
\
) as an escape character.