2016-11-04 3 views
0

文字列内の最初と最後の文字列の間の文字列を取得しようとしていますが、私のためには機能しません。私は次のことを試してみました与えられた文字列の最初と最後のアンダースコアの間の文字列を取得する方法はありますか?

gbox_asset_locations_list => asset_locations 
gbox_company_list => company 
gbox_country_states_cities_list => country_states_cities 
string_company_1_string => company_1 

$(function() { 
 
    var str = 'gbox_asset_locations_list'; 
 
    var result = str.substring(str.lastIndexOf('_') + 1, str.lastIndexOf('_')); 
 
    
 
    $('body').append(str + ' => ' + result); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

しかし、私はしませんでしたので、動作していない入力=>出力の例を以下の表に見てみましょう適切な出力を得る、私はこれを得るために私を助けることができますか?私が間違っていることは何ですか?

var str = 'gbox_asset_locations_list'; 
 
var result = str.substring(str.indexOf('_') + 1, str.lastIndexOf('_')); 
 

 
console.log(result) 

+1

なぜ「firstIndexOf()」を使って*最初の*アンダースコアを探していますか? –

+0

@kevinternetは '=>'の後の文字列です – ReynierPM

答えて

2

が、正規表現を使用する方が簡単ではないでしょう:

2

がいることをしてみてください? 「最初のアンダースコア、可能な限りあらゆる種類のその後など、多くの文字、その後、別のアンダースコア」

$(function() { 
    var str = 'gbox_asset_locations_list'; 
    var result = str.match(/_(.*)_/)[1]; 

    $('body').append(str + ' => ' + result); 
}); 

正規表現マッチ。結果として「多くの文字」を取得します。

+0

問題は.IndexOf(....)から来て、.indexOf(...)でなければなりません。 –

0
(function() { 
    var strs = ['gbox_asset_locations_list', 'gbox_company_list', 'gbox_country_states_cities_list', 'string_company_1_string'] 

    var res = []; 
    var _str; 

    strs.map(function(item, idx) { 
    _str = item.substring(item.indexOf('_')+1, item.lastIndexOf('_')); 
    res.push(_str); 
    document.querySelector('#results').innerHTML += res[idx] +'<br>'; 
    }.bind(this)); 
}())