代码之家  ›  专栏  ›  技术社区  ›  Apple Orange

如何使用javascript在特定值之前获取所有内容

  •  1
  • Apple Orange  · 技术社区  · 6 年前

    我有一个变量叫 overall . 这个变量有内容,但我想从以前的特定字符串中获取内容。我需要一个字符串中“使用”之前的所有内容。

    var overall = "Lorem ipsum is placeholder text commonly used in the graphic";
    alert(split(overall));
    
    function split(str) {
      var i = str.indexOf("used");
    
      if (i > 0)
        return str.slice(0, i);
      else
        return "";
    } {
      var i = str.indexOf("used");
    
      if (i > 0)
        return str.slice(0, i);
      else
        return "";
    }
    1 回复  |  直到 6 年前
        1
  •  3
  •   Zakaria Acharki    6 年前

    你可以简单地用特定的词来分隔( used 在您的情况下),这将返回 array 共两列:

    • 第一个包含单词前的内容
    • 第二部分是最后一部分

    然后你可以得到第一部分的分裂 string 使用索引 0 ,比如:

    var overall = "Lorem ipsum is placeholder text commonly used in the graphic";
    
    console.log(overall.split('used')[0]); //Lorem ipsum is placeholder text commonly 
    console.log(overall.split('used')[1]); // in the graphic