最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

How to concatenate string within class name syntax in JavaScript? - Stack Overflow

matteradmin8PV0评论

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.

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.

Share Improve this question edited Jul 10, 2018 at 6:08 Di437 asked Jul 10, 2018 at 5:56 Di437Di437 1833 silver badges12 bronze badges 4
  • In class's quotes or between <i> tags? – ClaudiusDan Commented Jul 10, 2018 at 6:00
  • Sorry, inside the class, its a font-awesome icon. It'll be something like "fa fa-building" – Di437 Commented Jul 10, 2018 at 6:02
  • Answer below will do the job, – ClaudiusDan Commented Jul 10, 2018 at 6:02
  • <i class=""></i>'.replace('""', '"' + icon + '"') might do the job. – RobG Commented Jul 10, 2018 at 6:16
Add a ment  | 

2 Answers 2

Reset to default 5

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

You can split it using .split() function.

  const icon = 'Idk'
  var str = '<i class = "">';
  var strSplit = str.split('"');
  var addString = strSplit[0] + '"' + icon + '"' + strSplit[2];
  console.log(addString);

The array strSplit contains ['<i class = ','','>']

Post a comment

comment list (0)

  1. No comments so far