Split a string from the first occurrence of a character

I have several lines of text in the log files in this format:

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

How can I split a line from the first comma so that I have a subject and the rest of the message in two different variables?

I tried using such a split, but it does not work when there are more commas in the message part.

[topic, message] = whole_message.split(",", 2);
+5
source share
6 answers

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

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

[1]it is a topic, it [2]is a message.

+12
source

Such a decomposition of the destination does not work in Javascript (currently). Try the following:

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

edit β€” ok, "split()" ; :

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

javascript String.split() ( , , split()).

An example of this behavior:

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

but not

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

as you expected.

Try using this split function:

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
source

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

(if you don't like doing something complicated)

+1
source

Why not separate it by a comma, take the object [0] as a topic, and then remove the topic (+,) from the original line?

You can:

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

(using prototype.js)

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

(using jQuery)

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

Or faster go with josh.trow

0
source

All Articles