3

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"?

3
  • 2
    Do you want to remove the character 2, or whatever character is in the 7th position? Will it always be a single character that is being removed, or will it sometimes be more than one character? Commented May 28, 2014 at 23:03
  • 1
    Why not just str.replace("-2","")? Commented May 28, 2014 at 23:03
  • 3
    Please read how to ask a good question. This question attracted a lot of answers before it was clarified, and even now there are multiple ways to interpret what is being asked, and unspecified requirements. Commented May 28, 2014 at 23:51

4 Answers 4

14

This would work:

var str = "SHELF-2-1-1".split('-2').join('');
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, that's a smart answer! I was trying to solve it based on the code user3271040 put in his question, but yours circumvents that and is really simple. I'll remember that kind of approach!!
what if in this case, "SHELF-2-1-1-2" it gives as "SHELF-1-1", while it should be "SHELF-1-1-2"
9

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

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

3 Comments

This is the cleanest answer IMO
It turns "SHELF-2-10-20" into "SHELF-100" which may not be wanted. And it's possible that only the first instance is supposed to be replaced. The question is quite unclear.
No, it turns "SHELF-2-10-20" into "SHELF-10-20". By default. replace only replaces the first occurrence. To perform a global replace, the first parameter needs to be a regular expression with the g flag applied.
4
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

Comments

-2
 let str = "Hello India";

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.