0

I am trying to get the string between the first and last _ in a given string but is not working for me. Take a look to the following table with examples of input => output:

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

I have tried the following:

$(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>

But is not working since I didn't get the proper output, can any help me to get this working? What I am doing wrong?

2
  • 1
    Why are you using lastIndexOf() to locate the first underscore? Commented Nov 4, 2016 at 12:56
  • @kevinternet is the string after the => Commented Nov 4, 2016 at 12:57

3 Answers 3

2

Wouldn't it be easier to use a regular expression?

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

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

The regex matches 'first an underscore, then as many characters of any kind as possible, then another underscore'. You then take the 'many characters' as the result.

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

Comments

2

try that :

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

console.log(result)      

Comments

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));
}())

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.