Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape a space in a file path in Node.js

Tags:

javascript

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 Node.js?

For example:

var input = JSON.parse('{ "path": "/foo/bar bam/baz.html" }');
input.path.replace(/(\s)/g, '\\$1');
like image 486
Ben Aston Avatar asked Jun 24 '17 16:06

Ben Aston


People also ask

How do you escape space in Javascript?

You just need: string. replace(/ \//g,"\n"); so that you're matching a space followed by an (escaped) forward slash.


2 Answers

var input = JSON.parse('{ "path": "/foo/bar bam/baz.html" }');

console.log(input.path.replace(/(\s+)/g, '\\$1'));
like image 195
Dinesh undefined Avatar answered Oct 03 '22 09:10

Dinesh undefined


Update your .replace regular expression as follows:

var input = JSON.parse('{ "path": "/foo/bar bam/baz.html" }');
console.log(input.path.replace(/(\s+)/g, '\\$1'));
like image 42
Scott Marcus Avatar answered Oct 01 '22 09:10

Scott Marcus