Javascript is split only once and ignores the rest

I am parsing a pair of key values ​​separated by colons. The problem is that there are colons in the values ​​section that I want to ignore, but the split function selects them anyway.

Example:

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

On separate lines, I tried this line.split(/:/, 1) , but only matched the data value part. Then I tried line.split(/:/, 2) , but it gave me ['description', 'this string is not escaped'] , and I need a whole line.

Thanks for the help!

+7
source share
5 answers
 a = line.split(/:/); key = a.shift(); val = a.join(':'); 
+12
source

Use the low-fat operator ( ? ) To split only the first instance.

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

+10
source

If you prefer the alternative to regexp, think about this:

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

Link: split , slice , join .

+2
source

A little more elegant:

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

Perhaps this approach would be best for this purpose:

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

Thus, you can use tables in your configuration / data files of such a structure, and also not worry about spaces before or after the name separator ':' .

Or you can use the primitive and fast string functions indexOf and substr to achieve your goal, in my opinion, in the fastest way (CPU and 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 } 
0
source

All Articles