Skip to content

Instantly share code, notes, and snippets.

@cocoastorm
Last active August 29, 2019 18:25
Show Gist options
  • Save cocoastorm/fed17da2c13781f66455c07b024b289c to your computer and use it in GitHub Desktop.
Save cocoastorm/fed17da2c13781f66455c07b024b289c to your computer and use it in GitHub Desktop.
Parse Search String

Parse Search String

Given a search string like (eg. Github Issue Search):

subject: hi bye text: yes no

Parse it:

input:  subject: hi bye text: yes no

key:  subject
value:  hi bye

key:  text
value:  yes no

This repeatedly tries searching the string with this regex: /(\w+):\s?/. I'm pretty sure there's a better way of doing this.

#!/usr/bin/env node
const re = /(\w+):\s?/g;
const txt = 'subject: hi bye text: yes no';
console.log('input: ', txt);
console.log();
let matches;
const ms = [];
while ((matches = re.exec(txt)) !== null) {
ms.push(matches);
}
ms.forEach((m, i) => {
let nextIdx = ms[i + 1] && ms[i + 1].index;
if (!nextIdx) {
nextIdx = txt.length;
}
const key = m[1];
const value = txt.substring(m.index + key.length + 1, nextIdx);
console.log('key: ', key.trim());
console.log('value: ', value.trim());
console.log();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment