【问题标题】:How to get substring from string after last seen to specific characer in javascript?如何在最后一次看到javascript中的特定字符后从字符串中获取子字符串?
【发布时间】:2016-09-04 16:49:18
【问题描述】:

我想从最后一个索引匹配空间的字符串中获取子字符串并将其放入另一个字符串中:

例如 如果我有:var string1="hello any body from me";

在 string1 中我有 4 个空格,我想在 string1 中的最后一个空格之后得到这个词,所以在这里我想得到“我”这个词...... 我不知道 string1 中的空格数......所以在最后一次看到特定字符后如何从字符串中获取子字符串?

【问题讨论】:

标签: javascript string substring


【解决方案1】:

您可以使用split 方法尝试类似的操作,其中input 是您的字符串:

var splitted = input.split(' ');
var s = splitted[splitted.length-1];

var splitted = "hello any body from me".split(' ');
var s = splitted[splitted.length-1];
console.log(s);

【讨论】:

    【解决方案2】:

    使用split 使其成为数组并获取最后一个元素:

    var arr = st.split(" "); // where string1 is st
    var result = arr[arr.length-1];
    console.log(result);
    

    【讨论】:

      【解决方案3】:

      或者只是:

      var string1 = "hello any body from me";
      var result = string1.split(" ").reverse()[0];
      console.log(result); // me
      

      感谢逆向方法

      【讨论】:

        【解决方案4】:

        我会使用正则表达式来避免数组开销:

        var string1 = "hello any body from me";
        var matches = /\s(\S*)$/.exec(string1);
        if (matches)
            console.log(matches[1]);

        【讨论】:

          【解决方案5】:

          您可以使用split 方法将字符串按给定的分隔符拆分,在这种情况下为“”,然后得到返回数组的最终子字符串。

          如果你想使用字符串的其他部分,这是一个很好的方法,而且它也很容易阅读:

          // setup your string
          var string1 = "hello any body from me";
          
          // split your string into an array of substrings with the " " separator
          var splitString = string1.split(" ");
          
          // get the last substring from the array
          var lastSubstr = splitString[splitString.length - 1];
          
          // this will log "me"
          console.log(lastSubstr);
          
          // ...
          
          // oh i now actually also need the first part of the string
          // i still have my splitString variable so i can use this again!
          
          // this will log "hello"
          console.log(splitString[0]);

          如果你喜欢写得又快又脏,这是一个不需要其余子字符串的好方法:

          // setup your string
          var string1 = "hello any body from me";
          
          // split your string into an array of substrings with the " " separator, reverse it, and then select the first substring
          var lastSubstr = string1.split(" ").reverse()[0];
          
          // this will log "me"
          console.log(lastSubstr);

          【讨论】:

            猜你喜欢
            • 2021-08-22
            • 1970-01-01
            • 2012-04-02
            • 2012-09-16
            • 2012-12-28
            • 2014-10-03
            相关资源
            最近更新 更多