2016-11-04 88 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>

但因为我没有不工作得到正确的输出,任何可以帮助我得到这个工作?我做错了什么?

+1

为什么使用'lastIndexOf()'定位* first *下划线? –

+0

@kevinternet是'=>' – ReynierPM

回答

2

那岂不是更容易使用正则表达式?

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

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

正则表达式匹配的第一个下划线,然后尽可能多的任何种类的作为可能的,那么另一下划线的字符'。然后,您将采用“多个角色”作为结果。

2

尝试:

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

 
console.log(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)); 
}()) 
相关问题