How to Use Strings in JavaScript?

Estimated read time 2 min read

In JavaScript, strings are used to represent text and are surrounded by either single or double quotes:

var singleQuotedString = 'Hello, world!';
var doubleQuotedString = "Hello, world!";

Both single and double quotes can be used to define a string, but you have to use the opposite type of quote within the string if you want to include a quote of the same type within the string:

var stringWithSingleQuotes = "Hello, world! It's a nice day.";
var stringWithDoubleQuotes = 'Hello, world! I said "Good morning".';

There are several methods available for manipulating strings in JavaScript:

  • length: Returns the length of the string
var str = "Hello, world!";
console.log(str.length); // outputs 13
  • concat: Joins two or more strings together
var str1 = "Hello";
var str2 = "world";
var joinedString = str1.concat(" ", str2, "!");
console.log(joinedString); // outputs "Hello world!"
  • toUpperCase: Converts the string to uppercase
var str = "Hello, world!";
var upperCaseString = str.toUpperCase();
console.log(upperCaseString); // outputs "HELLO, WORLD!"
  • toLowerCase: Converts the string to lowercase
var str = "Hello, world!";
var lowerCaseString = str.toLowerCase();
console.log(lowerCaseString); // outputs "hello, world!"
  • indexOf: Searches for a specified value in a string and returns the position of the first occurrence
var str = "Hello, world!";
var index = str.indexOf("world");
console.log(index); // outputs 7
  • substring: Extracts a specified portion of a string
var str = "Hello, world!";
var subString = str.substring(7, 12);
console.log(subString); // outputs "world"

These are just a few of the methods available for manipulating strings in JavaScript. For more information, you can refer to the official JavaScript documentation.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply