如何在JavaScript中连接类名语法中的字符串?(How to concatenate string within class name syntax in JavaScript?)

编程入门 行业动态 更新时间:2024-10-28 16:29:57
如何在JavaScript中连接类名语法中的字符串?(How to concatenate string within class name syntax in JavaScript?)

我有一个像这样的巨大字符串:

'<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); 
  
 

更多推荐

本文发布于:2023-04-28 02:05:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329863.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   语法   如何在   JavaScript   syntax

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!