如何获取给定字符串中第一个和最后一个下划线之间的字符串?

时间:2016-11-04 12:54:38

标签: javascript jquery

我正在尝试在给定字符串中的第一个和最后一个_之间获取字符串,但不适合我。请参阅下表,其中包含input =>的示例输出:

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>

但由于我没有得到正确的输出,因此无法正常工作,有什么能帮我解决这个问题吗?我做错了什么?

3 个答案:

答案 0 :(得分:2)

试试:

&#13;
&#13;
<com.google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id">
    </com.google.android.gms.ads.AdView>



    AdView mAdView = (AdView) findViewById(R.id.adView);
            AdRequest adRequest = new AdRequest.Builder()
                    .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                    .addTestDevice(getString(R.string.admob_test_device))
                    .build();
            mAdView.loadAd(adRequest);
&#13;
&#13;
&#13;

答案 1 :(得分:2)

使用正则表达式会不会更容易?

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

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

正则表达式匹配'首先是下划线,然后是尽可能多的任何类型的字符,然后是另一个下划线'。然后,您将“多个字符”作为结果。

答案 2 :(得分: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));
}())