String properties and methods in JS

String properties and methods in JS

Hey JavaScript developers! You’re probably familiar with strings, right? They might seem simple at first, but if not learned properly, they can cause confusion down the road. Understanding primitive strings is just the beginning—you also need to explore string properties and methods to work with them effectively.

In this article, we’ll dive into JavaScript string methods, breaking them down step by step. So, grab a cup of coffee, take a sip, and let’s explore the world of JavaScript strings together! 🚀

What is a string?

In simple terms, String is nothing but a collection of one or more characters. These characters can be alphabets, numbers or special characters. String data types is used to store data in text form. String is one of the 7 primitive data-types in JavaScript .

How to create a String?

In JavaScript you can create a string in 2 different ways:

1️⃣ Using String Literals:

The most common way to declare or create a string in JavaScript is by using string literals. In fact, throughout most of your JavaScript programming, you'll primarily be using this method to define strings.

const name = "Somraaj";
const height = '184.5cm';
const email = `user@example.com`;

I have written 3 examples here, and as you notice, all of them are slightly different from each other.

  1. You can use double quotes ( “ ” ), single quotes ( ‘ ’ ) or back ticks ( ) to create a string.

  2. A string can contain letters, numbers, and special characters as long as it is enclosed within quotes.

2️⃣ Using the String Constructor

You can also create a string using the String() constructor. But it does not return a primitive string. Instead, it’ll return an object .

let name = new String("Somraaj");
console.log(name); // [String: 'Somraaj']
console.log(typeof name); // "object"

As you can see, it returns a different data type and produces a different output.

🔴 Avoid using new String(), as it creates an object instead of a primitive string.

Later in this discussion, we'll explore how a String object differs from a primitive string. We'll also discuss why you should avoid using new String(), as it creates unnecessary complexity without significant benefits.

Convert to String:

While the methods mentioned earlier allow you to create a string, sometimes you may need to convert other data types into a string. To achieve this, JavaScript provides various built-in methods.

Here are the most common ways to convert a value into a string:

1️⃣ Using the String() Function

String() is a built-in function in JavaScript that converts other data types into strings. . Here is how you can use the String() syntax:

let age = 22;
let ageString = String(age);

2️⃣ Using .toString() Method

.toString() is a built in function in JavaScript. Most data types have a .toString() method that can be used for conversion.

console.log((22).toString());  // "22"

Output:

console.log(age) // output: 22
console.log(ageString)  //output: 22

Now you might think that nothing happened both have the same output. Well nothing was to change with the output anyways. Converting a number to a string doesn’t change its value, but it does change its data type.

console.log(typeof age); //output:  number
console.log(typeof ageString); //output: string

Since ageString is now a string, arithmetic operations behave differently compared to a number.

Changed behavior

console.log(age + 1); //output: 23
console.log(ageString + 1);  //output: 221

We will discuss more about it later in the article.

Some other examples of string conversion:

console.log((true).toString()); // "true"
console.log([1,2,3].toString()); // "1,2,3"

Yes you can convert an array or a Boolean value to a string as well.

NOTE: .toString() does not work on null or undefined.

const x = null;
const y = undefined;
console.log(x.toString()); // ❌ TypeError
console.log(y.toString()); // ❌ TypeError

But does String() constructor works on null or undefined? 🤔 Well find out yourself. 🧑‍💻

String properties

There are many built in string methods in JavaScript. That we can use to perform many operations.

📏 .length 📏:

.length property is used to identify the length of a string.

const name = "Somraaj"
console.log(name.length); // output: 7

String indexing:

Before I discuss about the next methods, let me explain how indexing works in String. Just like most of the Programming languages in JavaScript strings’ indexing starts from 0 instead of 1.

That means the position of the first character in a string is denoted as ‘0’:

Here is the visual representation:

And yes in string a space is also considered as a character and it takes an index.

String methods:

🔎.charAt(): 🔍

.charAt() is a JavaScript string method that returns the character at a specified position (index) in a string.

const name = "Somraaj"
console.log(name.charAt(2)); // output: "m"

🪑 .indexOf(): 🪑

.indexOf() identifies the index of a given character in a string.

const name = "Somraaj"
console.log(name.indexOf("m")); // output: 2

Notice how , when I entered a character it returned a number(index of that character)

NOTE: If one character repeats itself in the string then .indexOf() will return the index of the first one. Here is an example:

const name = "Somraaj Majumdar Rohan"
console.log(name.indexOf("a")); // output: 4

Observe how it returned only the index of the first character.

🪑 string[n]: 🪑

const name = "Somraaj"
console.log(name[3]); // output: "r"

🍕 slice(): 🍰

slice() is used to extract the part of a string and return the extracted part in a new string without modifying the original string.

Syntax:


string.slice(startIndex, endIndex)
  • The startIndex is the position where extraction begins.

  • The endIndex is optional. If provided, extraction stops before this index (endIndex is not included).

Example:

const name = "Somraaj Majumdar Rohan";
const serName = name.slice(8, 16);
console.log(serName) // output: Majumdar

As you can notice

  • slice(8, 16) starts extracting from index 8 and stops at index 15 . As you can see 16th element on endIndexis ignored and only till elements on endIndex*-1* are extracted

  • The character at index 16 or element onendIndex is not included in the extracted string.

What If you don’t give the endIndexinput? If you omit the endIndex, slice() extracts from the start index to the end of the string:

const restName = name.slice(8);
console.log(restName) // output: Majumdar Rohan

Since no endIndex is provided, slice(8) extracts everything from index 8 to the end of the string.

🚇.substr() 🚉

.substr() Behave almost same as slice(), except, instead of giving endIndex we give length as 2nd input. Here length means from the startIndex how many characters do I want to extract.

Syntax:

StringName.subStr(startIndex, length)

Example:

const name = "Somraaj Majumdar Rohan";
const nameExtracted = name.subStr(8, 7);
console.log(nameExtracted) // output: Majumdar

If you omit the endIndex?

Just like .slice() if you don’t put the endIndex, It’ll return the rest of the string.

const name = "Somraaj Majumdar Rohan";
const nameExtracted = name.subStr(8);
console.log(nameExtracted) // output: Majumdar Rohan

🔠 .toUpperCase() 🔠

.**toUpperCase()** as the name suggests, takes a string and returns a string is converted to upper case.

const name = "Somraaj Majumdar Rohan";
const nameUpperCase = name**.toUpperCase()**;
console.log(nameUpperCase) // output: SOMRAAJ MAJUMDAR ROHAN

🔡 .toLowerCase() 🔡

.**toLowerCase()** as the name suggests, takes a string and returns a string is converted to lower case.

const name = "Somraaj Majumdar Rohan";
const nameLowerCase = name**.toLowerCase()**;
console.log(nameLowerCase) // output: somraaj majumdar rohan

🔚 endsWith(): 🔚

The .endsWith() method checks whether a string ends with a specified character or substring. It returns a Boolean value:

  • true → if the string ends with the given substring. ✅

  • false → if it does not. ❌

Here is an example:

jsx
CopyEdit
const name = "Somraaj Majumdar Rohan";

console.log(name.endsWith("Rohan"));  // Output: true
console.log(name.endsWith("an"));     // Output: true
console.log(name.endsWith("Majumdar")); // Output: false

🔹 As you can see:

  • The string "Somraaj Majumdar Rohan" ends with "Rohan", so the first check returns true.

  • It also ends with "an", so the second check returns true.

  • "Majumdar" is in the middle, not at the end, so the third check returns false.

NOTE: .endsWith() is case-sensitive.

Using length parameter:

Another way of checking is providing a length parameter.

const sentence = "JavaScript is awesome";
console.log(sentence.endsWith("is", 13)); // Output: true

Here in the string “is” is the last subString till 13th index. So it returned true.

🔰startswith(): 🔰

The .startsWith() method checks whether a string starts with a specified character or substring. It returns a Boolean value:

  • true → if the string starts with the given substring. ✅

  • false → if it does not. ❌

Here is an example:

const name = "Somraaj Majumdar Rohan";

console.log(name.startsWith("Somraaj"));  // Output: true
console.log(name.startsWith("So"));     // Output: true
console.log(name.startsWith("Majumdar")); // Output: false

🔹 As you can see:

  • The string "Somraaj Majumdar Rohan" **starts with "**Somraaj**"**, so the first check returns true.

  • It also starts with "So", so the second check returns true.

  • "Majumdar" is in the middle, not at the start, so the third check returns false.

NOTE: .startsWith() is case-sensitive.

➰.includes(): ➰

.includes() takes a sub-string as an input and returns whether a string contains a specified substring or not in Boolean form.

  • true → if the sub-string exists in the string. ✅

  • false → if it does not. ❌

Here is an example:

let name = "Somraaj Majumdar"
console.log(name.includes("Somraaj")); // output: true
console.log(name.includes("And")); // output: false
  • As you can see "Somraaj" substring exists in name string so it returned true.

  • "And" substring does not exist in name string so it returned false.

Using the start Parameter

By default the start parameter is 0.

const message = "Hello, welcome to coding!";
console.log(message.includes("welcome", 10)); // false (search starts from index 10)
console.log(message.includes("welcome", 5));  // true (search starts from index 5)

NOTE: .include() is case sensitive.

🎗️ .replace(): 🎗️

.replace() method takes two parameters as input. The first parameter must be a substring that the original string contains. Then the .replace() method will replace the first substring with the second input.

Here’s the syntax:

stringName.replace("1stInput", "2ndInput");

Here’s an example:

const name = "Somraaj Majumdar Rohan";
console.log(name.replace("Somraaj", "Lazy")); //output: Lazy Majumdar Rohan

NOTE: .replace() replaces the first first substring of the string…If the string contains same substring again later in it, .replace will ignore it.

const paragraph = "I think Ruth's dog is cuter than your dog!";

console.log(paragraph.replace("dog", "monkey")); // output: I think Ruth's monkey is cuter than your dog!

🎗️ .replaceAll(): 🎗️

.replaceAll() is basically same as .replace() but on steroids 💉💉. Unlike .replace() .replaceAll() replaces all the substring having same value instead of ignoring them

const paragraph = "I think Ruth's dog is cuter than your dog!";

console.log(paragraph.replaceAll("dog", "monkey")); // output: I think Ruth's monkey is cuter than your monkey!
let url = "<https://x.com/home?lang=en>";
console.log(url.replaceAll("/", "-")); // output: https:--x.com-home?lang=en

🪓 .split(): 🪓

The .split() method splits a string into an array of substrings based on a specified delimiter. It does not modify the original string and returns a new array.

Splitting by Comma:

const text = "apple,banana,orange";
const fruits = text.split(",");
console.log(fruits); 
// Output: ["apple", "banana", "orange"]

Splitting by Space:

const sentence = "Hello World, welcome to JavaScript!";
const words = sentence.split(" ");
console.log(words);
// Output: ["Hello", "World,", "welcome", "to", "JavaScript!"]

Just as shown earlier you can use comma, space or any special character as specified delimiter.

✂️ .trim(): ✂️

.trim() method is used to remove extra spaces from the start and the end.

Here’s an example:

let name = "   Somraaj     ";
console.log(name);        // output:    Somraaj     
console.log(name.trim()); // output: Somraaj

Look how the .trim() method removed extra spaces.

NOTE: .trim() only removes the spaces from start and end of the string not from the middle of string. Here is an example:

let name = "Somr       aaj";   
console.log(name.trim()); // output: Somr       aaj

➕ .concat(): ➕

.concat method add two or more strings. and return a new one.

Here’s an example:

let firstName = "Somraaj";
let serName = "Majumdar";

console.log(firstName.concat(serName)); //output: SomraajMajumdar

to add multiple string:

let firstName = "Somraaj";
let serName = "Majumdar";
let lastName = "Rohan";

console.log(firstName.concat(" ", serName, " ", lastName)); //output: Somraaj Majumdar Rohan

Just like this you can add as many strings as you want.

💲String interpolation: 💲

String Interpolation is a technique used to embed variables inside a string. In JavaScript, this is achieved using template literals, which are defined using backticks (```) instead of single (') or double (") quotes. Before string interpolation we used to use , and + to embed variables in a string

let firstName = "Somraaj";
let serName = "Majumdar";

console.log("Hello! I am", firstName, serName); //output: Hello! I am Somraaj Majumdar
console.log("Hello! I am " + firstName + " " + serName); //output: Hello! I am Somraaj Majumdar

But this was not a very great way to embed variables in string. So there came string interpolation:

Here’s the syntax of String interpolation

let firstName = "Somraaj";
let serName = "Majumdar";

console.log(`Hello! I am ${firstName} ${serName}`); //output: Hello! I am Somraaj Majumdar

As you can see:

  • we used back ticks ( ) instead of ( “ “ or ‘ ‘ );

  • we used ${} to store the variables.

you can used any data types:

let age = 22;
console.log(`I am ${age} years old`); //ouput: I am 22 years old

Here’s a question for you:

If strings in JavaScript are primitive data types and not objects, how can we still use properties and methods on them, since properties and methods are typically associated with objects?(Do your own research and answer)

Conclusion:

There are many more string methods in JavaScript, and covering all of them in a single article isn’t possible. However, we have discussed the most essential ones that you’ll frequently use in your JavaScript programming journey.

To dive deeper into strings and explore additional methods, visit the MDN Web Docs.

Now, it’s your turn! Practice what you’ve learned—experiment with different string methods, try out new combinations, and explore their behavior in various scenarios.

📌 Remember: Reading articles or watching tutorials will only take you halfway. The real learning happens when you write code, experiment, and debug.

So go ahead—write, test, and master strings in JavaScript!

🚀 Happy Coding! 😊