Search code examples
javascript

Escape a space in a file path string


I receive a file path string via JSON.parse, but I need to escape the spaces in the string with backslashes.

How should I do this idiomatically in Javascript?

For example:

var input = JSON.parse('{ "path": "/foo/bar bam/baz.html" }');
input.path.replace(/(\s)/g, '\\$1');

Solution

  • var input = JSON.parse('{ "path": "/foo/bar bam/baz.html" }');
    
    console.log(input.path.replace(/(\s+)/g, '\\$1'));