Skip to content

JavaScript string Object | Basics

  • by

JavaScript string holds primitive type values which is a sequence of characters. JavaScript treats primitive values as objects when executing methods and properties.

Strings can be created as primitives, from string literals, or as objects, using the String() constructor:

//string literal
const str= "A string primitive";

//string object (using new keyword)
const str= new String("A String object");

So, JavaScript string Object methods and properties (length, substring(), etc). To find the length of a string, use the built-in length property:

JavaScript string examples

Simple example code strings are created by surrounding them with quotes.

<!DOCTYPE html>
<html>
<body>
  <script>
    const n1 = 'Mike';
    const n2 = "Jack";
    const res = `The names are ${n1} and ${n2}`;

    console.log(typeof(res))
    console.log(res)
  </script>
</body>
</html> 

Output:

JavaScript string Object

Single quotes and double quotes are practically the same and you can use either of them.

Backticks are generally used when you need to include variables or expressions into a string. This is done by wrapping variables or expressions with ${variable or expression} as shown above.

The string cannot be change

You can’t change the strings because JavaScript strings are immutable.

let a = 'hello';
a[0] = 'H';
console.log(a); // "hello"

But you can assign the variable name to a new string.

let a = 'hello';
a = 'Hello';
console.log(a); // "Hello"

Multiline Strings

Use the + operator or the \ operator to get the multiline string.

// using the + operator
const message1 = 'This is a long message ' +
    'that spans across multiple lines' + 
    'in the code.'

// using the \ operator
const message2 = 'This is a long message \
that spans across multiple lines \
in the code.'

JavaScript String Methods

MethodDescription
charAt(index)returns the character at the specified index
concat()joins two or more strings
replace()replaces a string with another string
split()converts the string to an array of strings
substr(start, length)returns a part of a string
substring(start,end)returns a part of a string
slice(start, end)returns a part of a string
toLowerCase()returns the passed string in lower case
toUpperCase()returns the passed string in upper case
trim()removes whitespace from the strings
includes()searches for a string and returns a boolean value
search()searches for a string and returns a position of a match

Do comment if you have any doubts or suggestions on this Js string topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *