我有一个像这样的巨大字符串:
'<i class=""></i>'我有一个名为icon的变量。 我需要在两个引号之间放置icon 。 虽然感觉很简单,但我一直在努力绕过它。 有人可以帮忙吗? JS新手在这里。
I have a huge string like this:
'<i class=""></i>'I have a variable called icon. I need to place icon in between the two quotes. Although it feels simple, I've been struggling to wrap my head around it. Can someone please help? JS newbie here.
最满意答案
你的字符串的分隔符是' ,所以只需结束' ,连接icon ,然后恢复' :
const icon = 'myIcon'; const str = '<i class="' + icon + '"></i>'; console.log(str);但是你可能会发现使用模板文字更具可读性,特别是如果你正在构建一个HTML字符串,或者它是多行的,或者如果你遇到转义字符有任何问题:用反引号开始和结束字符串,并通过将变量放在${varNameHere}插入变量:
const icon = 'myIcon'; const icon2 = 'myIcon2'; const icon3 = 'myIcon3'; const str = ` <i class="${icon}"></i> <i class="${icon2}"></i> <i class="${icon3}"></i> `; console.log(str);The delimiters of your string are ', so just end the ', concatenate the icon, and resume the ':
const icon = 'myIcon'; const str = '<i class="' + icon + '"></i>'; console.log(str);But you might find it more readable to use a template literal instead, especially if you're building an HTML string, or if it's multi-line, or if you're having any issues with escape characters: begin and end the string with backticks, and insert variables by putting them inside of ${varNameHere}:
const icon = 'myIcon'; const icon2 = 'myIcon2'; const icon3 = 'myIcon3'; const str = ` <i class="${icon}"></i> <i class="${icon2}"></i> <i class="${icon3}"></i> `; console.log(str);
更多推荐
发布评论