77

好的,这是我的代码,其中包含我尝试执行的操作的详细信息:

var str = "Hello m|sss sss|mmm ss";
//Now I separate them by "|"
var str1 = str.split("|");

//Now I want to get the first word of every split-ed sting parts:

for (var i = 0; i < codelines.length; i++) {
  //What to do here to get the first word of every spilt
}

那我应该在那里做什么?:\

我想要得到的是:

  • firstword[0]会给"Hello"

  • firstword[1]会给"sss"

  • firstword[2]会给"mmm"
4

12 回答 12

89

使用正则表达式

var totalWords = "foo love bar very much.";

var firstWord = totalWords.replace(/ .*/,'');

$('body').append(firstWord);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

于 2017-10-29T11:07:31.200 回答
72

用空格再次分割:

var firstWords = [];
for (var i=0;i<codelines.length;i++)
{
  var words = codelines[i].split(" ");
  firstWords.push(words[0]);
}

或者使用String.prototype.substr()(可能更快):

var firstWords = [];
for (var i=0;i<codelines.length;i++)
{
  var codeLine = codelines[i];
  var firstWord = codeLine.substr(0, codeLine.indexOf(" "));
  firstWords.push(firstWord);
}
于 2013-09-01T12:26:11.793 回答
18

我正在使用这个:

function getFirstWord(str) {
        let spaceIndex = str.indexOf(' ');
        return spaceIndex === -1 ? str : str.substr(0, spaceIndex);
    };
于 2015-07-24T16:21:33.490 回答
14

获取字符串的第一个单词,您可以这样做:

let myStr = "Hello World"
let firstWord = myStr.split(" ")[0]
console.log(firstWord)

split(" ")会将您的字符串转换为单词数组(子字符串是使用空格作为分隔符分割字符串产生的),然后您可以使用 [0] 获取访问第一个数组元素的第一个单词。

查看更多关于拆分方法的信息。

于 2021-02-04T16:51:59.493 回答
6

使用下划线js怎么样

str = "There are so many places on earth that I want to go, i just dont have time. :("
firstWord = _.first( str.split(" ") )
于 2016-10-01T03:15:22.627 回答
4

对先前答案的改进(处理多行或选项卡式字符串):

String.prototype.firstWord = function(){return this.replace(/\s.*/,'')}

使用searchand substr

String.prototype.firstWord = function(){let sp=this.search(/\s/);return sp<0?this:this.substr(0,sp)}

或者 没有正则表达式:

String.prototype.firstWord = function(){
  let sps=[this.indexOf(' '),this.indexOf('\u000A'),this.indexOf('\u0009')].
   filter((e)=>e!==-1);
  return sps.length? this.substr(0,Math.min(...sps)) : this;
}

例子:

String.prototype.firstWord = function(){return this.replace(/\s.*/,'')}
console.log(`linebreak
example 1`.firstWord()); // -> linebreak
console.log('space example 2'.firstWord()); // -> singleline
console.log('tab	example 3'.firstWord()); // -> tab

于 2018-05-28T09:38:07.660 回答
3
var str = "Hello m|sss sss|mmm ss"
//Now i separate them by "|"
var str1 = str.split('|');

//Now i want to get the first word of every split-ed sting parts:

for (var i=0;i<str1.length;i++)
{
    //What to do here to get the first word :)
    var firstWord = str1[i].split(' ')[0];
    alert(firstWord);
}
于 2013-09-01T12:31:43.080 回答
2

这段代码应该让你第一个词,

var str = "Hello m|sss sss|mmm ss"
//Now i separate them by "|"
var str1 = str.split('|');

 //Now i want to get the first word of every split-ed sting parts:

 for (var i=0;i<str1.length;i++)
 {
     //What to do here to get the first word :(
     var words = str1[i].split(" ");
     console.log(words[0]);
 }
于 2013-09-01T12:31:32.247 回答
2

在现代 JS 中,这被简化了,你可以这样写:

const firstWords = str =>
  str .split (/\|/) .map (s => s .split (/\s+/) [0])

const str = "Hello m|sss sss|mmm ss"

console .log (firstWords (str))

我们首先在 the 上拆分字符串|,然后在任何空白处拆分结果数组中的每个字符串,只保留第一个。

于 2020-01-02T18:36:11.697 回答
2

我很惊讶没有提到这种方法:"Some string".split(' ').shift()


直接回答问题:

let firstWords = []
let str = "Hello m|sss sss|mmm ss";
const codeLines = str.split("|");

for (var i = 0; i < codeLines.length; i++) {
  const first = codeLines[i].split(' ').shift()
  firstWords.push(first)
}
于 2020-02-06T01:48:30.557 回答
1
const getFirstWord = string => {
    const firstWord = [];
    for (let i = 0; i < string.length; i += 1) {
        if (string[i] === ' ') break;
        firstWord.push(string[i]);
    }
    return firstWord.join('');
};
console.log(getFirstWord('Hello World'));

或简化它:

const getFirstWord = string => {
    const words = string.split(' ');
    return words[0];
};
console.log(getFirstWord('Hello World'));
于 2020-11-10T07:56:05.497 回答
0

这段代码应该让你第一个词,

const myName = 'Jahid Bhuiyan';
console.log(myName.slice(0, myName.indexOf(' ')));

Ans 将是“Jahid”

于 2022-02-20T07:55:39.100 回答