【问题标题】:How do I split a string, breaking at a particular character?如何拆分字符串,在特定字符处中断?
【发布时间】:2021-07-20 14:59:48
【问题描述】:

我有这个字符串

'john smith~123 Street~Apt 4~New York~NY~12345'

使用 JavaScript,将其解析成最快的方法是什么

var name = "john smith";
var street= "123 Street";
//etc...

【问题讨论】:

    标签: javascript string-split


    【解决方案1】:

    使用 JavaScript 的 String.prototype.split 函数:

    var input = 'john smith~123 Street~Apt 4~New York~NY~12345';
    
    var fields = input.split('~');
    
    var name = fields[0];
    var street = fields[1];
    // etc.
    

    【讨论】:

      【解决方案2】:

      根据 ECMAScript6 ES6,干净的方法是解构数组:

      const input = 'john smith~123 Street~Apt 4~New York~NY~12345';
      
      const [name, street, unit, city, state, zip] = input.split('~');
      
      console.log(name); // john smith
      console.log(street); // 123 Street
      console.log(unit); // Apt 4
      console.log(city); // New York
      console.log(state); // NY
      console.log(zip); // 12345

      您可能在输入字符串中有额外的项目。在这种情况下,您可以使用 rest 运算符获取其余的数组或忽略它们:

      const input = 'john smith~123 Street~Apt 4~New York~NY~12345';
      
      const [name, street, ...others] = input.split('~');
      
      console.log(name); // john smith
      console.log(street); // 123 Street
      console.log(others); // ["Apt 4", "New York", "NY", "12345"]

      我假设值是只读引用,并使用了const 声明。

      享受 ES6!

      【讨论】:

      • 您也可以跳过一个项目:const [name, , unit, ...others] = ...
      【解决方案3】:

      你不需要 jQuery。

      var s = 'john smith~123 Street~Apt 4~New York~NY~12345';
      var fields = s.split(/~/);
      var name = fields[0];
      var street = fields[1];
      

      【讨论】:

      • 您不需要将正则表达式添加到这个简单的替换中。如果有的话,它只会让它变慢。您可以将其更改为引号以进行简单的字符串替换。
      【解决方案4】:

      即使这不是最简单的方法,您也可以这样做:

      var addressString = "~john smith~123 Street~Apt 4~New York~NY~12345~",
          keys = "name address1 address2 city state zipcode".split(" "),
          address = {};
      
      // clean up the string with the first replace
      // "abuse" the second replace to map the keys to the matches
      addressString.replace(/^~|~$/g).replace(/[^~]+/g, function(match){
          address[ keys.unshift() ] = match;
      });
      
      // address will contain the mapped result
      address = {
          address1: "123 Street"
          address2: "Apt 4"
          city: "New York"
          name: "john smith"
          state: "NY"
          zipcode: "12345"
      }
      

      ES2015 更新,使用解构

      const [address1, address2, city, name, state, zipcode] = addressString.match(/[^~]+/g);
      
      // The variables defined above now contain the appropriate information:
      
      console.log(address1, address2, city, name, state, zipcode);
      // -> john smith 123 Street Apt 4 New York NY 12345
      

      【讨论】:

      • 首先我们有一个由'~'符号分隔的字符串和一个keys的数组。第二个替换函数使用[^~]+ 匹配每个不同的部分(即“123 Street”、“Apt 4”等)并为每个部分调用该函数,并将其作为参数传递。在每次运行时,该函数从 keys 数组中获取第一个键(也使用 Array.unshift 将其删除)并将键和部分分配给地址对象。
      【解决方案5】:

      您需要查看 JavaScript 的 substrsplit,因为这不是真正适合 jQuery 的任务。

      【讨论】:

        【解决方案6】:

        如果找到了拆分器,那么只有

        它会拆分它

        否则返回相同的字符串

        function SplitTheString(ResultStr) {
            if (ResultStr != null) {
                var SplitChars = '~';
                if (ResultStr.indexOf(SplitChars) >= 0) {
                    var DtlStr = ResultStr.split(SplitChars);
                    var name  = DtlStr[0];
                    var street = DtlStr[1];
                }
            }
        }
        

        【讨论】:

          【解决方案7】:

          嗯,最简单的方法是这样的:

          var address = theEncodedString.split(/~/)
          var name = address[0], street = address[1]
          

          【讨论】:

            【解决方案8】:

            你可以使用split来分割文字。

            您也可以使用match,如下所示

            var str = 'john smith~123 Street~Apt 4~New York~NY~12345';
            matches = str.match(/[^~]+/g);
            
            console.log(matches);
            document.write(matches);

            正则表达式[^~]+ 将匹配除~ 之外的所有字符,并以数组的形式返回匹配项。然后,您可以从中提取匹配项。

            【讨论】:

            【解决方案9】:

            类似:

            var divided = str.split("/~/");
            var name=divided[0];
            var street = divided[1];
            

            这可能是最简单的

            【讨论】:

            • 不,您想要split("~")split(/~/),但不是split("/~/")。后者只会拆分"John/~/Smith" 而不会拆分"John~Smith"
            【解决方案10】:

            JavaScript 中的split() 方法用于将字符串转换为数组。 它需要一个可选参数,作为一个字符,在其上进行拆分。在你的情况下(~)。

            如果 splitOn 被跳过,它将简单地将字符串放在数组的第 0 位。

            如果 splitOn 只是一个“”,那么它将转换单个字符的数组。

            所以在你的情况下:

            var arr = input.split('~');
            

            将在arr[0] 获得名称,在arr[1] 获得街道。

            您可以在以下位置阅读更详细的说明 Split on in JavaScript

            【讨论】:

              【解决方案11】:

              Zach 说得对。使用他的方法,您还可以创建一个看似“多维”的数组。我在 JSFiddle http://jsfiddle.net/LcnvJ/2/ 上创建了一个快速示例

              // array[0][0] will produce brian
              // array[0][1] will produce james
              
              // array[1][0] will produce kevin
              // array[1][1] will produce haley
              
              var array = [];
                  array[0] = "brian,james,doug".split(",");
                  array[1] = "kevin,haley,steph".split(",");
              

              【讨论】:

                【解决方案12】:

                这个string.split("~")[0]; 搞定事情。

                来源:String.prototype.split()


                另一种使用 curry 和函数组合的函数式方法。

                所以第一件事就是拆分功能。我们想把这个"john smith~123 Street~Apt 4~New York~NY~12345"变成这个["john smith", "123 Street", "Apt 4", "New York", "NY", "12345"]

                const split = (separator) => (text) => text.split(separator);
                const splitByTilde = split('~');
                

                所以现在我们可以使用我们专门的splitByTilde 函数了。示例:

                splitByTilde("john smith~123 Street~Apt 4~New York~NY~12345") // ["john smith", "123 Street", "Apt 4", "New York", "NY", "12345"]
                

                要获取第一个元素,我们可以使用list[0] 运算符。让我们构建一个first 函数:

                const first = (list) => list[0];
                

                算法是:用冒号分割,然后得到给定列表的第一个元素。所以我们可以组合这些函数来构建我们最终的getName 函数。使用reduce 构建compose 函数:

                const compose = (...fns) => (value) => fns.reduceRight((acc, fn) => fn(acc), value);
                

                现在用它来编写splitByTildefirst 函数。

                const getName = compose(first, splitByTilde);
                
                let string = 'john smith~123 Street~Apt 4~New York~NY~12345';
                getName(string); // "john smith"
                

                【讨论】:

                  【解决方案13】:

                  用纯 Javascript 试试

                   //basic url=http://localhost:58227/ExternalApproval.html?Status=1
                  
                   var ar= [url,statu] = window.location.href.split("=");
                  

                  【讨论】:

                    【解决方案14】:

                    JavaScript:将字符串转换为数组 JavaScript 拆分

                        var str = "This-javascript-tutorial-string-split-method-examples-tutsmake."
                     
                        var result = str.split('-'); 
                         
                        console.log(result);
                         
                        document.getElementById("show").innerHTML = result; 
                    <html>
                    <head>
                    <title>How do you split a string, breaking at a particular character in javascript?</title>
                    </head>
                    <body>
                     
                    <p id="show"></p> 
                     
                    </body>
                    </html>

                    https://www.tutsmake.com/javascript-convert-string-to-array-javascript/

                    【讨论】:

                      【解决方案15】:

                      由于逗号问题的拆分与此问题重复,因此在此处添加。

                      如果您想在一个字符上进行拆分并处理可能跟在该字符后面的额外空格(这通常与逗号一起出现),您可以使用replace 然后split,如下所示:

                      var items = string.replace(/,\s+/, ",").split(',')
                      

                      【讨论】:

                        【解决方案16】:

                        这不如解构答案好,但是看到这个问题是 12 年前提出的,我决定给它一个在 12 年前也可以工作的答案。

                        function Record(s) {
                            var keys = ["name", "address", "address2", "city", "state", "zip"], values = s.split("~"), i
                            for (i = 0; i<keys.length; i++) {
                                this[keys[i]] = values[i]
                            }
                        }
                        
                        var record = new Record('john smith~123 Street~Apt 4~New York~NY~12345')
                        
                        record.name // contains john smith
                        record.address // contains 123 Street
                        record.address2 // contains Apt 4
                        record.city // contains New York
                        record.state // contains NY
                        record.zip // contains zip
                        

                        【讨论】:

                          【解决方案17】:

                          使用此代码--

                          function myFunction() {
                          var str = "How are you doing today?";
                          var res = str.split("/");
                          
                          }
                          

                          【讨论】:

                            猜你喜欢
                            • 2023-03-05
                            • 1970-01-01
                            • 1970-01-01
                            • 2019-10-19
                            • 1970-01-01
                            • 1970-01-01
                            • 2015-12-18
                            相关资源
                            最近更新 更多