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);
Using the split() Method For example, if we put the limit as n (n >0), it means that the pattern will be applied at most n-1 times. Here, we'll be using space (” “) as a regular expression to split the String on the first occurrence of space.
Use the str. split() method with maxsplit set to 1 to split a string on the first occurrence, e.g. my_str. split('-', 1) . The split() method only performs a single split when the maxsplit argument is set to 1 .
To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.
Get the First Letter of the String You should use the charAt() method, at index 0, to select the first character of the string. NOTE: charAt is preferable than using [ ] (bracket notation) as str.
Use a regex that gets "everything but the first comma". So:
whole_message.match(/([^,]*),(.*)/)
[1]
will be the topic, [2]
will be the message.
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;
});
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."]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With