remove square brackets from string javascript

Removing Square Brackets from a String in JavaScript

Removing square brackets from a string in JavaScript is a common task that can be achieved in several ways. Here are some ways:

Using String.replace() Method

The simplest way to remove square brackets from a string in JavaScript is by using the String.replace() method. Here's how:


const str = '[Hello World]';
const newStr = str.replace(/\[|\]/g, '');
console.log(newStr); // Output: 'Hello World'

In the code above, we first define our string variable 'str'. Then, we use the replace() method with a regular expression that matches all square brackets "[" and "]" and replaces them with an empty string. We store the modified string in a new variable 'newStr' and output it to the console.

Using String.split() and Array.join() Methods

Another way to remove square brackets from a string is by using the split() and join() methods of an array. Here's how:


const str = '[Hello World]';
const newStr = str.split('[').join('').split(']').join('');
console.log(newStr); // Output: 'Hello World'

In the code above, we first define our string variable 'str'. Then, we use the split() method with "[" as a separator to split the string into an array. We then use the join() method with an empty string as a separator to join the array elements into a string. We repeat the same process for "]" to remove all square brackets from the string. We store the modified string in a new variable 'newStr' and output it to the console.

Using Regular Expressions

Another way to remove square brackets from a string is by using regular expressions. Here's how:


const str = '[Hello World]';
const newStr = str.replace(/[[\]]/g, '');
console.log(newStr); // Output: 'Hello World'

In the code above, we first define our string variable 'str'. Then, we use the replace() method with a regular expression that matches all square brackets "[" and "]" and replaces them with an empty string. We store the modified string in a new variable 'newStr' and output it to the console.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe