繁体   English   中英

如何在jquery中将字符串分成多个部分

[英]How can I divide a string into parts in jquery

我下面有这段代码,我只需要在自动完成功能的onSelect参数中将字符串分成几个部分

$(function(){
    $('#business_category').autoComplete({
        minChars: 2,
        source: function(term, response){
            term = term.toLowerCase();
            var countryName = $("select[name=country]").val();
            var data_search_term = $("input[name=business_category]").val();
            console.log(countryName);
            $.ajax({
                type: "POST",
                url: "ajax/businesses_search_terms_count.php",
                data: "countryName=" + countryName + "&searchTerm=" + data_search_term,
                dataType: "json",

                success: function(resp){
                    response(resp.data)                
                }
            });
        },
        onSelect: function(event, term, item) {
            console.log("searchedItem: " + term);
            var data_search_term = $("input[name=business_category]").val();
            $('#total-count').html(data_search_term);                   
        }
    });
});

现在,当用户选择任何类别时,我的输出是:( (Audio and video => 6,488) 但是我想要这样的输出:( (Audio and video) 所以我只想要一个带有类别字段的字符串而不是像=> 6,488这样的计数数字

您可以使用带有string.split()和string.trim()的纯JavaScript来实现您的目标

  var str = "(Audio and video => 6,488)";
  var res = str.split("=>")[0]; //Turn string into array splitting by '=>' and get the first element
  res = res.trim(); //Remove side spaces
  res += ')'; //add ')' to the end of the string
  console.log(res); //prints to console '(Audio and video)'

如@Donny所述,您可以使用纯Javascript实现它。 我的解决方案与他的解决方案非常相似,但我只想使用模板字符串共享一些更简洁的解决方案:

 const str = "(Audio and video => 6,488)"; console.log(`${str.split("=>")[0].trim()})`); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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