简体   繁体   English

在JavaScript中按逗号分隔的字符串分割值

[英]Split values by comma separated string in javascript

Here is my issue: 这是我的问题:

I have RadListBox and I'm trying to get the values and append them so the result would be displayed like that: '1,2,3,4' but I'm getting back : 1,2,3,4, Does anyone know how can I achieve that? 我有RadListBox,我试图获取值并将其附加,这样结果将显示为:“ 1,2,3,4”,但我回来了:1,2,3,4,有人吗知道我该怎么做到吗?

Problem starts here: 问题从这里开始:

var sbLocationsIDS = new StringBuilder();
             for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
                 sbLocationsIDS.append(LocationIDS.getItem(i).get_value()+ ",");  
             }

The result: sbLocationsIDS =1,2,3,4, instead of '1,2,3,4' 结果:sbLocationsIDS = 1,2,3,4,而不是'1,2,3,4'

The Rest of the Code: 其余代码:

 function openNewTab(url) {
         var captureURL = url;
         var win = window.open(captureURL, '_blank');
         win.focus();
     }

     function GetComparisonsReport(sender, args) {
         var isValid = Page_ClientValidate('validateComparisons');
         if (isValid) { // If its true is going to fire the rest of the code
             var SessionID = getUrlVars()["SessionID"];
             var companyCodeVal = document.getElementById("<%=hfC.ClientID%>").value;
             var LocationIDS = $find("<%=rlbSelectedLocation.ClientID %>");
             var CategoriesIDS = $find("<%=rlbSelectedCategory.ClientID %>");
             var fileType = $find("<%=rcbFileType.ClientID %>");
             var fromFirstPeriod = $find("<%=rdpFromFirstPeriod.ClientID %>");
             var toFirstPeriod = $find("<%=rdpToFirstPeriod.ClientID %>");
             var fromSecondPeriod = $find("<%=rdpFromSecondPeriod.ClientID %>");
             var toSecondPeriod = $find("<%=rdpToSecondPeriod.ClientID %>");;
              if (LocationIDS.get_items().get_count() < 0) {
                 radalert("Please choose locations and select the Add button.<h3 style='color: #ff0000;'></h3>", 420, 170, "Case Global Alert");
                 return;
             }
             if (CategoriesIDS.get_items().get_count() < 0) {
                 radalert("Please choose categories and select the Add button.<h3 style='color: #ff0000;'></h3>", 420, 170, "Case Global Alert");
                 return;
             }
             var fromFirstPeriodDateValSelected = fromFirstPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
             var toFirstPeriodDateValSelected = toFirstPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
             var fromSecondPeriodDateValSelected = fromSecondPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
             var toSecondPeriodDateValSelected = toSecondPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
             var fileTypeValSelected = fileType.get_selectedItem().get_value();


             var sbLocationsIDS = new StringBuilder();
             for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
                 sbLocationsIDS.append(LocationIDS.getItem(i).get_value()+ ",");  // The problem is here!!!
             }
             var sbCategoriesIDS = new StringBuilder();
             for (i = 0; i < CategoriesIDS.get_items().get_count(); i++) {
                 sbCategoriesIDS.append(CategoriesIDS.getItem(i).get_value() + ",");
             }
             var ComparisonsURL = (String.format("https://www.test.com/cgis/{0}/reports/ConnectTorptIncidentsCountByLocationInterval.asp?SessionID={1}&locString={2}&catString={3}&FromDate1={4}&&ToDate1={5}&FromDate2={6}&ToDate2={7}&ExportType={8}", companyCodeVal, SessionID, sbLocationsIDS, sbCategoriesIDS, fromFirstPeriodDateValSelected, toFirstPeriodDateValSelected, fromSecondPeriodDateValSelected, toSecondPeriodDateValSelected, fileTypeValSelected));
             openNewTab(ComparisonsURL);
         }
     }

     String.format = function () {
         // The string containing the format items (e.g. "{0}")
         // will and always has to be the first argument.
         var theString = arguments[0];
         // start with the second argument (i = 1)
         for (var i = 1; i < arguments.length; i++) {
             // "gm" = RegEx options for Global search (more than one instance)
             // and for Multiline search
             var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
             theString = theString.replace(regEx, arguments[i]);
         }
         return theString;
     }

     function getUrlVars() {
         var vars = {};
         var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
             vars[key] = value;
         });
         return vars;
     }

     // Initializes a new instance of the StringBuilder class
     // and appends the given value if supplied
     function StringBuilder(value) {
         this.strings = new Array("");
         this.append(value);
     }

     // Appends the given value to the end of this instance.
     StringBuilder.prototype.append = function (value) {
         if (value) {
             this.strings.push(value);
         }
     }

     // Clears the string buffer
     StringBuilder.prototype.clear = function () {
         this.strings.length = 1;
     }

     // Converts this instance to a String.
     StringBuilder.prototype.toString = function () {
         return this.strings.join("");
     }

The problem is your loop is appending , always even for the last item in the loop. 问题是您的循环正在追加,即使对于循环中的最后一项也总是如此。

You want to append only for all items other than the last. 您只想为除最后一项以外的所有其他项追加。 There are multiple ways to do that, simplest being: check if the current element is the last and if so, do not append , 有多种方法可以做到这一点,最简单的方法是:检查当前元素是否为最后一个元素,如果不是,则不追加,

    var sbLocationsIDS = new StringBuilder();
    for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
        sbLocationsIDS.append(LocationIDS.getItem(i).get_value()); //append only value
        if(i != (LocationIDS.get_items().get_count() -1)) { //if not last item in list
            sbLocationsIDS.append(","); //append ,
        }
    }

There are other ways to do it, and depending on what you want to do with the values in the future, these may be pretty useful. 还有其他方法可以执行此操作,并且根据将来要使用这些值做什么,这些方法可能会非常有用。 (I see that the append in your code is actually a call to join , so this is actually a simpler version) (我看到代码中的append实际上是对join的调用,因此这实际上是一个简单的版本)

Add the values of the list to a array and use Array.join : 将列表的值添加到数组并使用Array.join

var select = document.getElementById("locationId");
var options = select.options;
var optionsArray = [];
if(options) {
    for (var i=0; i<=options.length; i++) {
        //text is the text displayed in the dropdown. 
        //You can also use value which is from the value attribute of >option>
        optionsArray.push(options[i].text);  
    }
}
var sbLocationsIDS = optionsArray.join(",");

With JQuery, the above code becomes a bit more simple: 使用JQuery,上面的代码变得更加简单:

var optionsArray = [];
$("#locationId option").each(function(){
    optionsArray.push(options[i].text);
});
var sbLocationsIDS = optionsArray.join(",");

Actually, if you decide yo use JQuery, you can use jquery.map : (idea from Assigning select list values to array ) 实际上,如果您决定使用JQuery,则可以使用jquery.map :( 将选择列表值分配给array中的思想

 $(document).ready(function() { $("#b").click(function() { var sbLocationsIDS = jQuery.map($("#locationId option"), function(n, i) { return (n.value); }).join(","); alert(sbLocationsIDS); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="locationId"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <button id="b">Click</button> 

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

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