Skip to content
Advertisement

js Split array add space between words (not first)

I have a string Topic: Computer Science

And want to strip out topic: (but in fact I want this to work with any header on the string line) and return Computer Science.

I thought about splitting the components and then adding the spaces back in:

var subjectLine = thisLine.split(" ");

var subjectString = "";

for (i = 1; i < subjectLine.length; i++) {
    subjectString += subjectLine[i] + " ";
  }

But then I need to remove the last space from the string.

For each doesn’t work as I need to NOT have the first element appended.

I’m not sure how to do this in js so it is reusable for many different lines and topic names that can come from the subjectLine

Advertisement

Answer

After splitting the line, remove the first element from the array, then join the rest back together.

var thisLine = "Topic: Computer Science";
var subjectLine = thisLine.split(" ");
subjectLine.splice(0, 1);
var subjectString = subjectLine.join(" ");
console.log(subjectString);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement