简体   繁体   中英

How do I get an array of substrings from an array of strings?

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.

You could use split and map function

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

A simpler approach would be

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM