简体   繁体   中英

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

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

You might consider using a regular expression, it'll probably be a lot easier than working with arrays: match the non-space characters at the beginning of the string, followed by at least one space, and .replace with the empty string:

const subjectString = thisLine.replace(/^\S+\s+/, '');

 const transform = line => line.replace(/^\S+\s+/, ''); console.log(transform('Topic: Computer Science'));

You need to know where the heading stops and the real data starts. Then delete all characters up to that point.

So, for instance, if you know that the heading ends with a colon, then do:

 var line = "this is the topic: Computer Science"; var topic = line.replace(/^.*:\s*/, ""); console.log(topic);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM