Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
JavaScript Remove all '+' from array wherein every element is preceded by a + sign
When working with arrays containing strings that start with a '+' sign, you can remove these characters using JavaScript's map() method combined with replace().
Problem Statement
Let's say we have an array where every element is preceded by a '+' sign:
var studentNames = [ '+John Smith', '+David Miller', '+Carol Taylor', '+John Doe', '+Adam Smith' ];
Using map() with replace()
The map() method creates a new array by calling a function on each element. We use replace() to remove the '+' character:
var studentNames = [
'+John Smith',
'+David Miller',
'+Carol Taylor',
'+John Doe',
'+Adam Smith'
];
console.log("Original array:");
console.log(studentNames);
studentNames = studentNames.map(function (value) {
return value.replace('+', '');
});
console.log("After removing the + symbol:");
console.log(studentNames);
Original array: [ '+John Smith', '+David Miller', '+Carol Taylor', '+John Doe', '+Adam Smith' ] After removing the + symbol: [ 'John Smith', 'David Miller', 'Carol Taylor', 'John Doe', 'Adam Smith' ]
Alternative Methods
You can also use arrow functions for a more concise approach:
var studentNames = ['+John Smith', '+David Miller', '+Carol Taylor'];
// Using arrow function
var cleanNames = studentNames.map(name => name.replace('+', ''));
console.log(cleanNames);
// Using substring to remove first character
var cleanNames2 = studentNames.map(name => name.substring(1));
console.log(cleanNames2);
[ 'John Smith', 'David Miller', 'Carol Taylor' ] [ 'John Smith', 'David Miller', 'Carol Taylor' ]
Key Points
-
map()returns a new array without modifying the original -
replace('+',' ')removes only the first occurrence of '+' -
substring(1)removes the first character regardless of what it is
Conclusion
Use map() with replace() to efficiently remove '+' signs from array elements. This approach is clean and maintains array immutability.
Advertisements
