user3271040
user3271040

Reputation: 89

Split and join in JavaScript?

I have a String "SHELF-2-1-1-2-1", I need to remove "2" from that string and want the output to be "SHELF-1-1-2-1"

I tried:

var str = "SHELF-2-1-1-2-1";
var res = str.split("-");

How can I join the array to get "SHELF-1-1-2-1"?

Upvotes: 3

Views: 40519

Answers (4)

Goal
Goal

Reputation: 1

 let str = "Hello India";

 let split_str = str.split("");
 console.log(split_str);

 let join_arr = split_str.join("");
 console.log(join_arr);

Upvotes: -2

Ballbin
Ballbin

Reputation: 727

Sounds like you want to do a replace... Try:

var res = str.replace('-2', '');

Upvotes: 9

markasoftware
markasoftware

Reputation: 12662

var str = "SHELF-2-1-1";
var res = str.split("-");
res.pop(res.indexOf('2'));
var newStr = res.join('-');

This should also work for your updated question, as it will only remove the first 2 from the string

Upvotes: 4

Andrew Eisenberg
Andrew Eisenberg

Reputation: 28757

This would work:

var str = "SHELF-2-1-1".split('-2').join('');

Upvotes: 14

Related Questions