String Methods and Conversion

Explore essential JavaScript string methods with practical examples. Learn how to manipulate, extract, and convert strings and other data types in modern JavaScript.

Loading...
String Methods and Conversion

String Methods

JavaScript provides a rich set of methods to manipulate and work with strings.

Here are the most commonly used JavaScript string methods and their functionalities.

String length

If you want to find the number of characters in a string, then you can use the length property.

const str = "This is a string.";
const lengthOfStr = str.length;
console.log(lengthOfStr); // Output: 17

This also counts white spaces and special characters.

String toUpperCase()

If you want to convert a string to uppercase, then you can use the toUpperCase() method.

const str = "This is a string.";
const uppercaseStr = str.toUpperCase();
console.log(uppercaseStr); // Output: THIS IS A STRING.

String toLowerCase()

If you want to convert a string to lowercase, then you can use the toLowerCase() method.

const str = "This Is a String.";
const lowercaseStr = str.toLowerCase();
console.log(lowercaseStr); // Output: this is a string.

String indexOf()

If you want to find the first occurrence of a substring in a string, then you can use the indexOf() method.

const str = "This is a js string and js string is nice.";
const indexOfJs = str.indexOf("js");
console.log(indexOfJs); // Output: 10

If no occurrence is found, then it returns -1.

String lastIndexOf()

If you want to find the last occurrence of a substring in a string, then you can use the lastIndexOf() method.

const str = "This is a js string and js string is nice.";
const lastIndexOfJs = str.lastIndexOf("js");
console.log(lastIndexOfJs); // Output: 24

If no occurrence is found, then it returns -1.

String slice()

If you want to extract a part of a string, then you can use the slice() method.

This will return the extracted part in a new string.

Syntax:

string.slice(start position, end position);

The end position will not be included.

Example: 1

const str1 = "This is a string.";
 
// This will start slicing from index 0 up to 7 (but not including 7)
const slicedStr1 = str1.slice(0, 7);
 
console.log(slicedStr1); // Output: This is

Example: 2

const str2 = "This is a string.";
 
// This will start slicing from index 3 up to 9 (but not including 9)
const slicedStr2 = str2.slice(3, 9);
 
console.log(slicedStr2); // Output: s is a

If you don’t specify the end position, then this will slice out the rest of the string.

For example:

const str = "This is a string.";
const slicedStr = str.slice(5);
console.log(slicedStr); // Output: is a string.

You can also give it negative parameters.

For example:

const str = "This is a string.";
const slicedStr = str.slice(-3, -1);
console.log(slicedStr); // Output: ng

You can understand this as:

str.slice(-3, -1);
str.slice(str.length - 3, str.length - 1);
str.slice(17 - 3, 17 - 1);
str.slice(14, 16);

String substring()

The substring() method is similar to the slice() method, but the difference is that if you give it negative parameters (less than 0), then they will be treated as 0.

Example:

const str = "This is a string.";
const slicedStr = str.substring(-3, 5);
console.log(slicedStr); // Output: This

String substr()

The substr() method is similar to the slice() method, but the difference is that the end parameter is the length of the characters to be extracted.

const str = "This is a string.";
 
//This will extract the characters starting from index 11 and will extract 4 characters.
const slicedStr = str.substr(11, 4);
 
console.log(slicedStr); // Output: trin

Note: substr() is considered legacy and should be avoided in modern code. Prefer slice() or substring() instead.

String charAt()

If you want to get a character at a specified index in a string, then you can use the charAt() method.

const str = "This is a string.";
const character = str.charAt(13);
console.log(character); // Output: i

String concat()

If you want to concatenate two or more strings, then you can use the concat() method.

const firstName = "John";
const lastName = "Doe";
const fullName = firstName.concat(" ", lastName);
console.log(fullName); // Output: John Doe

String trim()

You can remove whitespace from both ends of a string using the trim() method.

const str = "    This is a string.    ";
const trimmedStr = str.trim();
console.log(trimmedStr); // Output: This is a string.

String replace()

If you want to replace a specified substring with another string, then you can use the replace() method.

const str = "JavaScript is amazing!";
const replacedStr = str.replace("amazing", "awesome");
console.log(replacedStr); // Output: JavaScript is awesome!

Note: Only the first occurrence is replaced unless a regex with /g is used.

For example:

let str = "Hello World";
const replacedStr = str.replace(/o/g, "0");
console.log(replacedStr); // "Hell0 W0rld" (global replace with regex)

String split()

You can convert a string into an array using the split() method.

Example 1: Using split() without a separator

When called without a separator, split() returns the entire string as a single-element array.

const str1 = "JavaScript is amazing!";
const arr1 = str1.split();
console.log(arr1); // Output: ['JavaScript is amazing!']

Example 2: Using split(" ") with space as a separator

Using a space " " as a separator splits the string into individual words in an array.

const str2 = "JavaScript is amazing!";
const arr2 = str2.split(" ");
console.log(arr2); // Output: ['JavaScript', 'is', 'amazing!']

You can split a string at both commas and semicolons using the split() method along with Regular Expressions.

Example:

const str = "mango,orange;apple,grape;kiwi";
const splitedStr = str.split(/[,;]/);
 
console.log(splitedStr);
// Output: [ 'mango', 'orange', 'apple', 'grape', 'kiwi' ]

How It Works:

  • split() Method: Splits a string into an array based on a specified pattern.
  • Regular Expression /[,;]/:
    • [,] matches a comma.
    • [;] matches a semicolon.
    • Combined [;,] matches both.

If you want to split a string at spaces, commas, semicolons, or even periods, you can extend the regular expression.

For example:

const str = "apple, banana; cherry orange. grape";
const splitedStr = str.split(/[,; .]+/);
 
console.log(splitedStr);
// Output: [ 'apple', 'banana', 'cherry', 'orange', 'grape' ]

Regular Expression /[,; .]+/:

  • [,; .] matches any of the characters: comma, semicolon, space, or period.
  • + means "one or more occurrences" of any of the specified characters.

More Useful String Methods

In addition to the basic methods, JavaScript provides several other powerful string methods for pattern matching, padding, trimming, and checking content.

String includes()

This method is used to check if a substring exists in a string. This is case-sensitive.

const str = "JavaScript is awesome";
console.log(str.includes("awesome")); // Output: true

String startsWith()

This method is used to check if a string starts with a given substring.

const str = "Hello World";
console.log(str.startsWith("Hello")); // Output: true

String endsWith()

This method is used to check if a string ends with a given substring.

const str = "Learn JavaScript";
console.log(str.endsWith("Script")); // Output: true

String repeat()

Repeats a string a specified number of times.

const str = "ha";
console.log(str.repeat(3)); // Output: "hahaha"

String padStart() / padEnd()

Adds padding to the start or end of a string until the desired length is reached.

"5".padStart(2, "0"); // Output: "05"
"5".padEnd(3, "*"); // Output: "5**"
  • "5".padStart(2, "0") pads the string "5" from the start until the total length becomes 2, using "0" as the padding character: "05".
  • "5".padEnd(3, "*") pads the string "5" from the end until the total length becomes 3, using "*" as the padding character: "5**".

String trimStart() and trimEnd()

These are similar to trim() but only remove whitespace from one side.

const str = "   Hello World!   ";
 
console.log(str.trimStart()); // Output: "Hello World!   "
console.log(str.trimEnd()); // Output: "   Hello World!"

String replaceAll()

Replaces all occurrences of a substring with another string.

const sentence = "red green red blue red";
const result = sentence.replaceAll("red", "pink");
 
console.log(result); // Output: "pink green pink blue pink"

String match() (with Regular Expressions)

Finds matches based on a regex pattern and returns them as an array.

const str = "I have 2 apples and 3 bananas.";
const matches = str.match(/\d+/g);
 
console.log(matches); // Output: ["2", "3"]

Here,

  • /\d+/g is a regular expression:
    • \d matches any digit (0–9).
    • + means one or more digits.
    • g is the global flag to find all matches in the string.
  • str.match(/\d+/g) returns an array of all digit sequences it finds in the string: ["2", "3"].

String search() (with Regular Expressions)

Returns the index of the first match based on a regex pattern. Returns -1 if not found.

const str = "I love JavaScript";
console.log(str.search(/java/i)); // 7

Here,

  • /java/i matches "java" case-insensitively (i flag).
  • It returns the index of the first match.
  • If no match is found, it returns -1.

String Conversion

In JavaScript, you often need to convert other data types (like numbers, booleans, objects) into strings. This is called string conversion.

Common Ways to Convert Other Data Types to String

1. Using String() Function (Constructor):

The global String() function converts any value (numbers, booleans, objects, null, and undefined) to a string.

const num = 123;
const bool = true;
const obj = { name: "Shefali" };
 
console.log(String(num)); // Output: "123"
console.log(String(bool)); // Output: "true"
console.log(String(obj)); // Output: "[object Object]"

2. Using .toString() Method:

Most JavaScript values (except null and undefined) have a .toString() method to convert them to strings.

const num = 123;
const bool = true;
 
console.log(num.toString()); // Output: "123"
console.log(bool.toString()); // Output: "true"

Note:

  • Calling .toString() on null or undefined will cause an error.
  • Objects may override .toString() to provide custom string output.

3. Using Template Literals:

Embedding variables inside template literals automatically converts them to strings.

const num = 123;
const bool = true;
 
console.log(`Number: ${num}`); // Output: "Number: 123"
console.log(`Boolean: ${bool}`); // Output: "Boolean: true"

4. Using String Concatenation:

Concatenating a value with a string forces conversion to a string.

const num = 123;
const bool = true;
 
console.log(num + ""); // Output: "123"
console.log(bool + ""); // Output: "true"

Things to Keep in Mind

  • null and undefined convert to "null" and "undefined" when using String() or concatenation.
  • Numbers like NaN and Infinity convert to "NaN" and "Infinity".
  • Objects convert to "[object Object]" by default, unless they override .toString().

Common Ways to Convert Strings to Other Data Types

1. Convert String to Number:

  • Using Number():

    Number("42"); // Output: 42
    Number("3.14"); // Output: 3.14
    Number("abc"); // Output: NaN
    Number(" "); // Output: 0
  • Using Unary + Operator:

    This method is more concise than Number().

    +"42"; // Output: 42
    +"3.14"; // Output: 3.14
    +"abc"; // Output: NaN
  • Using parseInt() and parseFloat():

    These methods extract numeric values from the beginning of the string.

    parseInt("100px"); // Output: 100
    parseFloat("3.14rem"); // Output: 3.14
    parseInt("abc"); // Output: NaN

2. Convert String to Boolean:

Boolean("true"); // Output: true
Boolean("false"); // Output: true
Boolean(""); // Output: false
Boolean("0"); // Output: true

In JavaScript, non-empty strings are always truthy, even "false" or "0".

3. Convert String to Array:

You can use .split() method to convert a string to an array.

"apple,banana,cherry".split(","); // Output: ["apple", "banana", "cherry"]
"hello".split(""); // Output: ["h", "e", "l", "l", "o"]

4. Convert String to Object (JSON):

You can use JSON.parse() to convert a JSON-formatted string into an object.

const jsonStr = '{"name":"Shefali","role":"developer"}';
const obj = JSON.parse(jsonStr);
console.log(obj); // Output: Object { name: "Shefali", role: "developer" }

Note: The string must be valid JSON, or it will throw an error.


Support my work!