2016-08-03 65 views
0

String.raw似乎是一個正確的方式來編寫嵌入式命令狀如何打印「 1」使用ES6 String.raw

const command = String.raw`sed -n 's/${hash} \(.*\)/\1/p' 

但是,這是行不通的,因爲\1不能在字符串寫入.RAW,問題如下所示:

我可以看到
console.log(String.raw`\1`) 
=>SyntaxError: Octal literals are not allowed in template strings. 

console.log(String.raw`\\1`) 
\\1 
+1

有這將允許這個建議:https://github.com/tc39/proposal-template-literal-revision – Bakkot

回答

1

只有這樣做,就

let x = '\\1' 
const command = String.raw`sed -n 's/${hash} \(.*\)/${x}/p'` 

@HBP一lmost在意見中提出的正確的判罰

const command = String.raw`sed -n 's/${hash} \(.*\)/${'\\1'}/p'` 

看起來是理想的

+0

我想想這也是唯一的解決方法,謝謝 – mko

+0

看來,你可以用''\ 1''替換'x',不需要新變量 – HBP

+0

你是什麼意思@HBP? '$ { '\ 1'}'?不太......但是,'$ {'\\ 1'}'工作 –