从第一次出现的字符中拆分字符串

时间:2011-05-25 21:30:11

标签: javascript regex split

我在这种格式的日志文件中有多行文本:

topic, this is the message part, with, occasional commas.

如何从第一个逗号中拆分字符串,以便将主题和其余信息放在两个不同的变量中?

我尝试过使用这种分割,但是当消息部分中有更多逗号时它不起作用。

[topic, message] = whole_message.split(",", 2);

6 个答案:

答案 0 :(得分:12)

使用正则表达式获取“除第一个逗号之外的所有内容”。所以:

whole_message.match(/([^,]*),(.*)/)

[1]将是主题,[2]将成为消息。

答案 1 :(得分:4)

那种分解的赋值在Javascript中不起作用(目前)。试试这个:

var split = whole_message.split(',', 2);
var topic = split[0], message = split[1];

编辑 - 确定所以“split()”有点破碎;试试这个:

var topic, message;
whole_message.replace(/^([^,]*)(?:,(.*))?$/, function(_, t, m) {
  topic = t; message = m;
});

答案 2 :(得分:3)

javascript' String.split()方法已被破解(至少如果您期望与其他语言split()方法提供的行为相同)。

此行为的一个示例:

console.log('a,b,c'.split(',', 2))
> ['a', 'b']

而不是

> ['a', 'b,c']
像你一样期待。

请尝试使用此拆分功能:

function extended_split(str, separator, max) {
    var out = [], 
        index = 0,
        next;

    while (!max || out.length < max - 1 ) { 
        next = str.indexOf(separator, index);
        if (next === -1) {
            break;
        }
        out.push(str.substring(index, next));
        index = next + separator.length;
    }
    out.push(str.substring(index));
    return out;
};  

答案 3 :(得分:2)

下面!

String.prototype.mySplit = function(char) { 
  var arr = new Array(); 
  arr[0] = this.substring(0, this.indexOf(char)); 
  arr[1] = this.substring(this.indexOf(char) + 1); 
  return arr; 
}

str = 'topic, this is the message part, with, occasional commas.'
str.mySplit(',');
-> ["topic", " this is the message part, with, occasional commas."]

答案 4 :(得分:1)

var a = whole_message.split(",");
var topic = a.splice (0,1);

(除非你喜欢复杂的做法)

答案 5 :(得分:0)

为什么不用逗号分割,将[0]项作为主题,然后从原始字符串中删除主题(+,)?

你可以:

var topic = whole_message.split(",")[0]

(使用prototype.js)

var message = whole_message.gsub(topic+", ", "") 

(使用jQuery)

whole_message.replace(topic+", ", "")

或者更快,请使用josh.trow

相关问题