-1

I have some strings that I'd like to manipulate with regex.

Input foo: bar hello: world cats: dogs

Output foo: 'bar' hello: 'world' cats: 'dogs'

Right now I know I can use Javascript's replace string method but I'm not sure about the regex to use

nandesuka
  • 699
  • 8
  • 22

1 Answers1

2

You could try the following regex replacement:

var input = "foo: bar hello: world cats: dogs";
var output = input.replace(/(\w+): (.*?)(?=\s+\w+:|$)/g, "$1: '$2'");
console.log(input + "\n" + output);

Note that while this approach happens to work well with the exact sample you provided, regex is not by itself a parsing tool, so this answer might not be suitable for nested content.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360