Javascript只拆分一次,其余的忽略

Javascript split only once and ignore the rest

本文关键字:一次 拆分 Javascript      更新时间:2023-09-26

我正在解析一些用冒号分隔的键值对。我遇到的问题是,在值部分中有一些我想忽略的冒号,但split函数无论如何都会拾取它们。

样本:

Name: my name
description: this string is not escaped: i hate these colons
date: a date

在各个行上,我尝试了这个line.split(/:/, 1)但它只匹配数据的值部分。接下来我尝试了line.split(/:/, 2)但这给了我['description', 'this string is not escaped'],我需要整个字符串。

感谢您的帮助!

a = line.split(/:/);
key = a.shift();
val = a.join(':');

使用贪婪运算符 ( ? ( 只拆分第一个实例。

line.split(/: (.+)?/, 2);

如果你更喜欢正则表达式的替代方案,请考虑以下情况:

var split = line.split(':');
var key = split[0];
var val = split.slice(1).join(":");

参考:拆分、切片、连接。

稍微优雅一点:

a = line.match(/(.*?):(.*)/);
key = a[1];
val = a[2];

也许这种方法是最适合这样的目的:

var a = line.match(/([^:'s]+)'s*:'s*(.*)/);
var key = a[1];
var val = a[2];

因此,您可以在这种结构的配置/数据文件中使用表格,也不必担心名称-值分隔符':'之前或之后的空格。

或者你可以使用原始和快速的字符串函数indexOfsubstr来实现你的目标,我认为,最快的方式(通过CPU和RAM(

for ( ... line ... ) {
    var delimPos = line.indexOf(':');
    if (delimPos <= 0) {
        continue; // Something wrong with this "line"
    }
    var key = line.substr(0, delimPos).trim();
    var val = line.substr(delimPos + 1).trim();
    // Do all you need with this  key: val
}

第一次出现时将字符串一分为二

拆分具有多个字符串的字符串,即仅在第一列出现时:
使用正面后视(?<=)

const a = "Description: this: is: nice";
const b = "Name: My Name";
console.log(a.split(/(?<=^[^:]*):/)); // ["Description", " this: is: nice"]
console.log(b.split(/(?<=^[^:]*):/)); // ["Name", " My Name"]

它基本上从字符串的开头^消耗所有不是列[^:] *零倍或更多次。完成正面回溯后,最终匹配列:

如果您还想删除列后面的一个或多个空格,
使用/(?<=^[^:]*): */

关于 Regex101.com

的说明
function splitOnce(str, sep) {
  const idx = str.indexOf(sep);
  return [str.slice(0, idx), str.slice(idx+1)];
}
splitOnce("description: this string is not escaped: i hate these colons", ":")