Use a library for this, instead of working with strings.
e.g. https://github.com/nodeca/js-yaml