首页 > 解决方案 > 如何使用javascript获取特定值之前的所有内容

问题描述

我有一个名为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 "";
}

标签: javascriptjquery

解决方案


您可以简单地按特定单词(used在您的情况下)进行拆分,这将返回array两列之一:

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

string然后您可以使用 index获得拆分的第一部分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


推荐阅读