javascript - 如何使用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 "";
}
解决方案
您可以简单地按特定单词(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
推荐阅读
- python - 电报机器人从文件发送随机图像
- node.js - Parcel SemVer 错误
- javascript - 将对象文件列表从 javascript 反序列化为 c#
- python - 当输入大小小于 PyTorch 中的目标大小时,F.adaptive_max_pool 如何工作?
- java - 阵列中最长的高原。我究竟做错了什么?
- html - 当浏览器下载 CSS 文件时,chrome 中的渲染引擎会发生什么?
- postgresql - PostgreSQL:如何运行从 SQL SELECT 语句返回的 ALTER 查询
- sql - 使用 SQL 查询获取从今天开始的最后 45 天
- asp.net-core - ASP.NET Core 3.1 中的 ParentId 错误?
- c# - BlockingCollection 分页到磁盘