admin管理员组

文章数量:1181432

I have multiple lines of text in log files in this kind of format:

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

How can I split the string from the first comma so I would have the topic and the rest of the message in two different variables?

I've tried using this kind of split, but it doesn't work when there's more commas in the message part.

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

I have multiple lines of text in log files in this kind of format:

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

How can I split the string from the first comma so I would have the topic and the rest of the message in two different variables?

I've tried using this kind of split, but it doesn't work when there's more commas in the message part.

[topic, message] = whole_message.split(",", 2);
Share Improve this question edited Jan 28, 2016 at 2:05 user4639281 asked May 25, 2011 at 21:30 SeerumiSeerumi 2,0373 gold badges19 silver badges16 bronze badges 5
  • 1 Why doesn't split(",", 2) work for you? – jjnguy Commented May 25, 2011 at 21:32
  • @jjnguy probably because that assignment statement is totally bogus :-) – Pointy Commented May 25, 2011 at 21:33
  • 2 JavaScript != Python :-) – Martijn Pieters Commented May 25, 2011 at 21:34
  • @jjnguy because if the whole message goes like "mighty topic, hi, I'm an user.", the topic variable would contain "mighty topic" and the message would contain only "hi" instead of "hi, I'm an user." – Seerumi Commented May 25, 2011 at 21:38
  • @Martijn: unless you are using a Javascript 1.7+ interpreter, CoffeScript or a Harmony interpreter, where destructuring assignment is available :) (and other Python-like features too) -- this might be what confused the OP. – gonchuki Commented May 25, 2011 at 21:43
Add a comment  | 

8 Answers 8

Reset to default 14

Use a regex that gets "everything but the first comma". So:

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

[1] will be the topic, [2] will be the message.

Here!

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."]

That sort of decomposing assignment doesn't work in Javascript (at the present time). Try this:

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

edit — ok so "split()" is kind-of broken; try this:

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

javascript's String.split() method is broken (at least if you're expecting the same behavior that other language's split() methods provide).

An example of this behavior:

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

and not

> ['a', 'b,c']

like you'd expect.

Try this split function instead:

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;
};  
var a = whole_message.split(",");
var topic = a.splice (0,1);

(unless you like doing things complicated ways)

Why not split by comma, take the [0] item as topic then remove the topic(+,) from the original string ?

You could:

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

(using prototype.js)

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

(using jQuery)

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

Or quicker, go with josh.trow

let string="topic, this is the message part, with occasional commas."

let arr = new Array(); 
let idx = string.indexOf(',')
arr[0] = string.substring(0, idx);
arr[1] = string.substring(idx+1);
let topic = arr[0];
let message = arr[1]

output arr should be: ["topic", "this is the message part, with occasional commas."]

Split using /,(.*)/ or rather /, *(.*)/ to account for the space after the comma

Example:

const str = "topic, this is, the, message."
const [topic, message] = str.split(/, *(.*)/);

console.log(topic);   // "topic"
console.log(message); // "this is, the, message."

本文标签: javascriptSplitting string from the first occurrence of a characterStack Overflow