JavaScript String Object
JavaScript strings are used for storing and manipulating text — they can consist of a sequence of letters, numbers and/or symbols. In this article, we’re going to first take a look at how we create strings, concatenate strings and we’ll see some fundamental syntax rules that apply to strings.
We’ll then be moving on to string manipulation, with many of the common methods such as: charAt()
, indexOf()
, slice()
, length
, toUpperCase()
, toLowerCase()
, split()
, trim()
, replace()
, parseInt()
, parseFloat()
and Number()
.
Creating Strings
There are three ways to write a string — with single quotes ‘ ’
, double quotes “ ”
or back-ticks ` `
. Let’s assign some strings to a myString
variable with each technique:
There is no syntactic difference between single or double quotes, you’re free to go with your preference — however it’s a good idea to stay consistent within your projects! However, back-ticks (known as template literals), have a few super powers which we’ll be taking a look at later in the article.
And of course the reason we assign strings to variables, is so they’re much easier to work with & manipulate within our programs!
Concatenation
We use string concatenation to combine two or more strings together to form a new string. We combine our strings using the +
operator.
Here we’ve combined two strings stored in separate variables into a new concat
variable. However, you’ll notice we have no space between the names in our new variable as concatenation joins strings end to end. To add the space, use a pair of quotes ‘ ’
like so:
Now we have our desired output!
Concatenation with Template Literals
When we use template literals ` `
, we no longer need to use the +
operator to concatenate. We include expressions and variables within our strings using the ${}
syntax . For example,
Template literals are much easier read & write.
Syntax Rules
Using Quotes and Apostrophes
Knowing that quotes “
and apostrophes ‘
are interpreted by JavaScript to mark where a string begins & ends. How can we include them within a string? For example:
The additional apostrophe in ’G
’
day Barry!'
is the problem. JavaScript thinks ‘G’
is the string and attempts to parse the rest as code, thus generating the error.
Using quotes within a string would cause the same error:
There are a number of ways we can avoid these errors…
Alternate your syntax
Use the opposite quote style to enclose any quotes or apostrophes within your strings, such as:
Whilst this technique works just fine. It’s preferable to be more consistent within our code.
Use the Escape Character \
By using a backslash we can prevent JavaScript from interpreting a quote as the end of the string. The \ should go before any single or double quote:
Use Template Literals
If we enclose our string in template literals ``
, our string will be valid and it’ll look much cleaner too:
Longer Strings
We use either the newline character \n
or carriage return \r
, to break longer strings up over multiple lines:
This works fine but it’s quite messy. We could tidy it up by using some concatenation:
Or go for a gold star with template literals:
Back-ticks to the rescue! No escapes or concatenation required, the newlines are preserved and it looks much neater.
Working with Strings
In this next section, we’ll look at some of the ways we can work with strings.
Each character in a string is numbered, starting at 0
. For example:
The first character is T
at index position 0
.
The last character is !
at index position 17
.
The spaces also have index positions at 4
, 7
and 10
.
We can access any character like so:
charAt()
We can similarly use the charAt()
method. It returns the character at the specified index in a string, such as:
indexOf()
We can use indexOf()
if we wish to return an index number.
It returns the index of where the substring starts in the string, or -1
if the substring isn’t found. It’s case-sensitive.
You can use a conditional to test if a substring exists:
This works as we know that -1
results when nothing is found, so logically any result greater than -1
would mean the substring exists.
slice()
To get a portion of a string starting (and optionally ending) at a particular character, we can use slice()
.
This method can take 2 arguments. The first is the start position (0
is of course the first character), and the second optional argument is the end position. If either argument is a negative number, it will start at the end of the string and work backwards.
Finding the Length of a String
To find the length of a string we can use the length
property. It returns the number of characters in a string.
The length
property is returns the actual number of characters starting with 1
, which in our example is 18
, not the final index number, which starts at 0
and ends at 17
.
Converting to Upper or Lower Case
The two methods toUpperCase()
and toLowerCase()
are useful ways to format our text.
toUpperCase()
converts all text in a string to uppercase.
toLowerCase()
converts all text in a string to lowercase.
split()
To divide a string up into sections & insert the contents into an array, we can use the split()
method.
The argument we provide is the delimiter
, the character that we’re using to split up our string.
In the below example, lets use the whitespace “ “
character as our delimiter:
We can now access each section via its array position..
We can also optionally provide a second argument to stop splitting a string, after a certain number of delimiter matches have been found.
Lets look at another example, this time using a comma ‘, ‘
as our delimiter.
Our .split(', '
, 2
)
stopped the split after the second comma, returning just the first two array entries.
trim()
The trim()
method removes any white space from both ends of a string, but importantly not anywhere in between.
Whitespace can be tabs or spaces, the trim()
method conveniently removes any excess.
replace()
If we wish to search through a string for a value, and replace it with a new value, we use replace()
.
The first parameter will be the value to find, and the second will be the replacement value.
By default, the replace()
method replaces the first match only. To replace all matches, you’ll need to pass in a regular expression using the global flag g
. If we also want to ignore case, we’d add the case insensitive flag i
.
Here we’re telling every instance of google within our string (regardless of case), to be replaced by “Google”.
Converting Strings into Numbers
In this final section, lets take a quick look at some of the ways we can convert strings into numbers.
parseInt()
To convert a string into an integer (a whole number) we can use parseInt()
. It takes two arguments, the first being the value we want to convert, and the second is called the radix. This is the base number used in mathematical systems. For our use, it should always be 10
, the decimal system.
parseFloat()
parseFloat()
If we wish to convert into a floating point number (a number with decimal points), we’d use parseFloat()
.
Number()
Number()
We can convert our strings with the Number()
method as well, however its stricter about which values it can convert. It only works with strings that consist of numbers.
NaN
if you recall — stands for Not a number.
Last updated
Was this helpful?