📒
SDV503
  • SDV503
  • Command Prompt
    • Windows Command Prompt
    • Mac OS Terminal
  • GIT & GITHub
    • GitHub
    • Git
      • Git Workflow
        • Forking Workflow
  • README
    • How to write a readme.md file?
    • Write a better README.me
    • Generate a README for GitHub Repo Quickly
  • Code-comments
    • Clean Comments
    • Writing Comments in a Good way
  • Pair Coding
    • What is Pair Coding?
    • Pair Programming Experience
  • Programming?
    • What is Programming?
    • What Is A Programming Paradigm?
    • JavaScript Programming Paradigms
  • Number Systems
    • Decimal and Binary numbers
  • JavaSCript
    • Introduction To JavaScript
      • The JavaScript Engine
  • JS Call Stack
    • JavaScript call stack
    • JavaScript & Memory
      • Memory Leaks in JavaScript
    • Execution Context and Execution Stack in Javascript
      • Javascript Execution Context and Hoisting
  • JavaScript Variables
    • Introduction to JS Data Types
    • Primitive and Non-Primitive
    • Operator precedence and associativity
      • JS Operators Part One
      • JS Operators Part Two
      • JS Operators Part Three
    • Clean Code for JS Variables
  • JavaScript Scopes
    • Scope (Chain) Visualized
  • Javascript  — this keyword
  • JavaScript Data Types
    • More JavaScript Data Types
  • JavaScript Expressions and Statements
  • if/else, switch and ternary operator
    • If/Else statement
  • Switch Statement
  • Ternary Operator
  • JavaScript Loops
    • Loops in JavaScript
      • Trouble With Loops
  • Objects
    • JavaScript Objects
      • Prototypal Inheritance Visualized
      • JavaScript Number Object
      • JavaScript String Object
  • Functions
    • JavaScript Function Part One
    • JavaScript Function Part Two
    • Immediately Invoked Function Expressions ~ IIFE
    • JS => Arrow Functions
    • JavaScript Callback
    • Hoisting in JavaScript
      • Hoisting Visualized
    • Recursion Functions
    • Curry and Function Composition
  • JavaScript Features
    • JSpread Operator
    • JavaScript Built-in Functions & Objects
  • Data Structures&Algorithms
    • JavaScript’s Data Types
    • Data Structures in JavaScript
      • Introduction to Big O Notation
      • Big O Notation in Javascript
      • Linked Lists
        • Linked Lists — 2
      • Hash Tables
      • Stack & Queue
  • TLDR
    • Single quotes (‘ ’) and double quotes (“ ”) in JavaScript
  • ES6
    • Generators and Iterators
    • Javascript Classes
    • JavaScript closures
    • JavaScript Promises & Async/Await
      • Event Loop Visualized
  • C#
    • What does C#? (C Sharp)
    • C# vs JavaScript
    • What Is The Difference Between C#, .NET, ASP.NET, Microsoft.NET, and Visual Studio?
    • What is the .NET Framework?
    • Methods and Properties of Console Class in C#
    • Datatypes in C#
    • C# Code Comments
    • The if statement
    • The switch statement
    • Loops
    • Comparison operators
    • Addition assignment operators
    • The String Interpolation Operator
    • Arrays
    • Lists
    • Dictionaries
Powered by GitBook
On this page
  • Creating Strings
  • Concatenation
  • Concatenation with Template Literals
  • Syntax Rules
  • Using Quotes and Apostrophes
  • Longer Strings
  • Working with Strings
  • charAt()
  • indexOf()
  • slice()
  • Finding the Length of a String
  • Converting to Upper or Lower Case
  • split()
  • trim()
  • replace()
  • Converting Strings into Numbers
  • parseInt()
  • parseFloat()
  • Number()

Was this helpful?

  1. Objects
  2. JavaScript Objects

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:

let myString = 'I am a string!';
let myString = "I am a string!";
let myString = `I am a string!`;

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.

const firstName = 'Barry';
const secondName = 'Dingus';const concat = firstName + secondName;console.log(concat);    // output: BarryDingus

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:

const concat = firstName + ' ' + secondName;console.log(concat);// output: Barry Dingus

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,

const fullName = 'Barry Dingus';
const location = 'Mullet Creek';const concat2 = `Welcome ${fullName}! We think ${location} is alright!`;console.log(concat2);// output: Welcome Barry Dingus! We think Mullet Creek is alright!

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:

const greeting = 'G'day Barry!';console.log(greeting);// Uncaught Syntax Error: Unexpected identifier

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:

const quote = 'Barry said 'I lost my keys'';console.log(quote);// Uncaught Syntax Error: Unexpected identifier

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:

'G'day Barry!'     // error
"G'day Barry!"     // correct'Barry said 'I lost my keys''   // error
'Barry said "I lost my keys"'   // correct
"Barry said 'I lost my keys'"   // correct

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:

'G\'day Barry!'   // correct'Barry said \'I lost my keys\''   // also correct!

Use Template Literals

If we enclose our string in template literals ``, our string will be valid and it’ll look much cleaner too:

`Barry said "I lost my keys" and "I'm now concerned"!`; // correct

Longer Strings

We use either the newline character \n or carriage return \r, to break longer strings up over multiple lines:

const multipleLines = "This string is long\nso lets display it\nacross multiple lines.";// output:"This string is long
so lets display it
across multiple lines."

This works fine but it’s quite messy. We could tidy it up by using some concatenation:

const multipleLines = "This string is long\n" +
"so lets display it\n" +
"across multiple lines.";

Or go for a gold star with template literals:

const multipleLines = `This string is long
so lets display it
across multiple lines.`;

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:

"This is my string!"            

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:

"This is my string![8]"     // m

charAt()

We can similarly use the charAt() method. It returns the character at the specified index in a string, such as:

"This is my string!.charAt(8)"     // m

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.

const str = "This is my string!";str.indexOf('s');       // returns 3 (the first 's' instance)str.indexOf('my');      // returns 8str.indexOf('My');      // returns -1str.lastIndexOf('s');   // returns 11 (the last instance)

You can use a conditional to test if a substring exists:

if (str.indexOf('my') > -1) {
	console.log('Success! It contains the string');
}

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.

const str = "This is my string!";str.slice(5);         // "is my string!"
str.slice(5, 10);     // "is my"
str.slice(0, -8);     // "This is my"

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.

"This is my string!".length;     //18

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.

const str = "This is my string!";
const upper = str.toUpperCase();
console.log(upper);// "THIS IS MY STRING!"

toLowerCase() converts all text in a string to lowercase.

const str = "This is my string!";
const lower = str.toLowerCase();
console.log(lower);// "this is my string!"

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:

const str = "This is my string!";
const splitString = str.split(" ");console.log(splitString);// ["This", "is", "my", "string!"]

We can now access each section via its array position..

splitSting[0];    // This
splitSting[1];    // is
splitSting[2];    // my
splitSting[3];    // string!

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.

const shoppingList = 'Bananas, green apples, chocolate, cat food';
const foodItems = shoppingList.split(', ');
console.log(foodItems);// ["Bananas", "green apples", "chocolate", "cat food"]
const snacks = shoppingList.split(', ', 2);
console.log(snacks)// ["Bananas", "green apples"]

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.

const ahhhhWhitespace = "     This is my string!     ";const trimmed = ahhhhWhitespace.trim();console.log(trimmed);// "This is my string!"

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.

const str = "This is my string!";const newString = str.replace("my", "your");console.log(newString);// This is your string!

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.

const str = "GOOGLE is my homepage. But I don't use google Chrome."const newString = str.replace(/google/gi, "Google");console.log(newString);// Google is my homepage. But I don't use Google Chrome.

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.

parseInt('64', 10);     // 64parseInt('64.9', 10);   // 64parseInt('64px', 10);   // 64

parseFloat()

If we wish to convert into a floating point number (a number with decimal points), we’d use parseFloat().

parseFloat('64.9');             // 64.9parseFloat('64bit');            // 64console.log(parseFloat('64'));  // 64

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.

Number('64');      // 64Number('64.9');    // 64.9Number('64bit');   // NaNNumber('64%');     // NaN

NaN if you recall — stands for Not a number.

PreviousJavaScript Number ObjectNextJavaScript Function Part One

Last updated 5 years ago

Was this helpful?