【问题标题】:Split string with limit, where last string contains the remainder使用限制拆分字符串,其中最后一个字符串包含余数
【发布时间】:2014-09-30 08:38:53
【问题描述】:

例如如果我运行这个 javascript:

var str = 'hello_world_there';
var parts = str.split('_', 2);

var p1 = parts[0];
var p2 = parts[1];

最后,p1 包含“hello”,p2 包含“world”。

我希望 p1 包含“hello”,p2 包含“world_there”。即我希望 p2 包含字符串的其余部分,无论它有多少下划线(类似于 c# 的 String.Split(char[] separator, int count) 的行为方式。

任何解决方法?

【问题讨论】:

    标签: javascript string split


    【解决方案1】:
    var str = 'hello_world_there';
    var parts = str.split('_');
    
    var p1 = parts[0];
    var p2 = parts.slice(1).join('_');
    

    这将进行普通拆分,然后合并第一个匹配之后的所有内容。

    【讨论】:

    • 如果你用str.split(/\s+/)这样的正则表达式拆分,然后将其更改为str.split(/(\s+)/)(例如在整个正则表达式周围添加括号),然后在上面的解决方案中使用slice(2).join("")而不是slice(1).join('_')。
    【解决方案2】:

    这与将其余部分保持原样略有不同,但这对我来说很有用:

    const [a, ...b] = 'foo/bar/baz'.split('/');
    // => a: 'foo', b: ['bar', 'baz']
    

    【讨论】:

      【解决方案3】:

      编写你自己的函数:

      function split(string, delimiter, n) {
          var parts = string.split(delimiter);
          return parts.slice(0, n - 1).concat([parts.slice(n - 1).join(delimiter)]);
      }
      

      【讨论】:

        【解决方案4】:

        试试看:

        var parts = str.split('_', 2);
        var p1 = parts.shift();
        var p2 = parts.join('_');
        

        或:

        var index = str.indexOf('_');
        var p1 = str.substr(0, index);
        var p2 = str.substr(index + 1);
        

        【讨论】:

          【解决方案5】:

          对于您只需要两个部分的特定情况,最简单的方法是indexOf 和substring:

          const index = text.indexOf("_");
          const p0 = index === -1 ? text : text.substring(0, index);
          const p1 = index === -1 ? "" : text.substring(index + 1);
          

          现场示例:

          const text = "hello_world_there";
          const index = text.indexOf("_");
          const p0 = index === -1 ? text : text.substring(0, index);
          const p1 = index === -1 ? "" : text.substring(index + 1);
          console.log(`p0 = "${p0}", p1 = "${p1}"`);

          我发现我经常需要它,我将它放在实用程序模块中:

          const twoParts = (str, delim = " ") => {
              const index = str.indexOf("_");
              if (index === -1) {
                  return [str, ""];
              }
              return [
                  str.substring(0, index),
                  str.substring(index + delim.length),
              ];
          };
          

          但是,如果您想做的不仅仅是两部分,那么一种不需要在事后重新加入字符串的方法是使用带有捕获组的正则表达式:

          const result = text.match(/^([^_]+)_+([^_]+)_+(.*)$/);
          const [_, p0 = "", p1 = "", p2 = ""] = result ?? [];
          

          现场示例:

          const text = "hello_world_xyz_there";
          const result = text.match(/^([^_]+)_+([^_]+)_+(.*)$/);
          const [_, p0 = "", p1 = "", p2 = ""] = result ?? [];
          console.log(`p0 = "${p0}", p1 = "${p1}", p2 = "${p2}"`);

          【讨论】:

            【解决方案6】:

            正则表达式解决方案(您可以将“|”更改为其他字符,例如“__”但不能更改为“_”)

            var [p1,p2] = str.replace(/_/,"|").split("|");
            

            let str = 'hello_world_there'
            let [p1,p2] = str.replace(/_/,"|").split("|");
            
            console.log("p1:",p1);
            console.log("p2:",p2);

            【讨论】:

            • 我喜欢你的态度,但这只会产生一个与其他随机角色相关的新问题,例如|
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-04-23
            • 1970-01-01
            • 2022-06-20
            • 1970-01-01
            • 2017-12-19
            • 1970-01-01
            相关资源
            最近更新 更多