在 Javascript 中,我想展平我的模板字符串。所以我想要这个:
const str = `
my name
is
frank
`
上交:
const str = 'my name is frank'
我之所以这么问是因为带有 `` 的大量空白导致 GET 请求 URL 中的错误,例如:
const url = `
http://0.0.0.0
:${port}/
apiCallName?
var1=${var1}
var2=${var2}
`
会变成巨大的东西,比如:
const url = '%20%20%20%20%20%20http://0.0.0.0%20%20%20%20%20%20:80/%20%20%20...'
这会中断通话。我不想使用 ' + var1 + '
构建字符串。我发现模板字符串读起来好多了,所以我想继续使用它们。
注意:它不应替换所有空格。因为有时我喜欢写带有空格的大字符串,比如:
const str = `
<label>This is label 1</label>
<button>This is button 1</button>
`
这不应该丢失空格,所以不是这样:
const str = '<label>Thisislabel1</label><button>Thisisbutton1</button>'
最佳答案
您可以使用 replace以及它的回调函数。
([ ]+)|(\n)
([ ]+)
- 一次或多次匹配空格字符。 ( g1 )|
- 与逻辑 OR 相同的交替。(\n+)
- 匹配换行符。 ( g2 )
const str = `
my name
is
frank
`
const op = str.replace(/([ ]+)|(\n+)/gm,function(match,g1,g2){
if(g1) return ' '
else return ''
})
console.log(op.trim())
关于javascript - 如何在 JavaScript 中展平模板字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54861873/