简体   繁体   English

js拆分数组在单词之间添加空格(不是第一个)

[英]js Split array add space between words (not first)

I have a string Topic: Computer Science我有一个字符串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.并想删除主题:(但实际上我希望它可以与字符串行上的任何 header 一起使用)并返回计算机科学。

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我不确定如何在 js 中执行此操作,因此它可用于可能来自 subjectLine 的许多不同行和主题名称

After splitting the line, remove the first element from the array, then join the rest back together.分割线后,从数组中删除第一个元素,然后将 rest 重新连接在一起。

 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:您可能会考虑使用正则表达式,它可能比使用 arrays 更容易:匹配字符串开头的非空格字符,后跟至少一个空格,并将.replace替换为空字符串:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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