我有一个名为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 "";
}
最佳答案
您可以简单地按特定单词拆分(在您的情况下为 used
),这将返回两列的 array
:
- 第一个包含词前的内容
- 第二个包含最后一部分
然后您可以使用索引 0
获取拆分后的 string
的第一部分,例如:
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
关于javascript - 如何使用javascript获取特定值之前的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51323718/