-1

I have an array of string like:

var myArray=['rwt-cable1','rwt-cable42','rwt-cable40',...]

But what I am really interested in is:

['cable1','cable42','cable40',...]

What would be the best way? I'm currently looping through items and extract substrings to get my output array.

2
  • 1
    I'd do a myArray.map(..), but yes, ultimately you need to loop and substring/regex-replace or something along those lines. Commented Apr 19, 2016 at 12:50
  • ['rwt-cable1', 'rwt-cable42', 'rwt-cable40'].forEach(function(elem, index) { ip[index] = elem.replace('rwt-', ''); }); Commented Apr 19, 2016 at 12:54

4 Answers 4

8

You could use split and map function

var res = ['rwt-cable1', 'rwt-cable42', 'rwt-cable40'].map(e => e.split('-')[1]);

console.log(res);

Sign up to request clarification or add additional context in comments.

3 Comments

I've removed the off-topic comments on this post. If you spot bad practices in code, feel free to edit those out as long as the meaning of the answer doesn't change. Changing the means of output while not touching the actual logic that makes the answer is fine.
that was pretty funny(those comments about document.write) ... the discussion could be endless ))
@MadaraUchiha document.body.textContent = res; seems to not work in Safari.
1

You can do it by using a regular expression:

var myArray= ['rwt-cable1','rwt-cable42','rwt-cable40'];
myArray = myArray.map(v => v.replace(/^rwt\-/,""));
console.log(myArray); //["cable1", "cable42", "cable40"]

The regex ^rwt\- will match the text rxt- at the beginning of the string.

1 Comment

You've got my vote for explicitly only targeting the beginning of the string.
1

The alternative using Array.map and Array.slice functions:

var myArray = ['rwt-cable1','rwt-cable42','rwt-cable40'],
    result = myArray.map(function(v){ return v.slice(4); });

console.log(result);   // ["cable1", "cable42", "cable40"]

Comments

1

A simpler approach would be

['rwt-cable1', 'rwt-cable42', 'rwt-cable40'].map(x => x.replace('rwt-', ''))
// ["cable1", "cable42", "cable40"]

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.