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!
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('-'); .
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.
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.
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.
a = line.split(/:/);
key = a.shift();
val = a.join(':');
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