Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript split only once and ignore the rest

I am parsing some key value pairs that are separated by colons. The problem I am having is that in the value section there are colons that I want to ignore but the split function is picking them up anyway.

sample:

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

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

Thanks for the help!

like image 643
babsher Avatar asked Apr 21 '11 16:04

babsher


People also ask

How do you split based on first occurrence?

Use the String. split() method with array destructuring to split a string only on the first occurrence of a character, e.g. const [first, ... rest] = str. split('-'); .

Is split faster than regex?

Regex will work faster in execution, however Regex's compile time and setup time will be more in instance creation. But if you keep your regex object ready in the beginning, reusing same regex to do split will be faster.

Does split return an array JavaScript?

The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.

How do you split something in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


1 Answers

a = line.split(/:/);
key = a.shift();
val = a.join(':');
like image 94
awm Avatar answered Sep 20 '22 21:09

awm