javascript 获取字符串的第一个单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18558417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:23:52  来源:igfitidea点击:

Get first word of string

javascriptsplit

提问by Sasuke Kun

Okay, here is my code with details of what I have tried to do:

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

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
}

So what should I do there? :\

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

What I want to get is :

我想得到的是:

  • firstword[0]will give "Hello"

  • firstword[1]will give "sss"

  • firstword[2]will give "mmm"
  • firstword[0]会给 "Hello"

  • firstword[1]会给 "sss"

  • firstword[2]会给 "mmm"

回答by ComFreek

Split again by a whitespace:

再次被空格分割:

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

Or use String.prototype.substr()(probably faster):

或者使用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);
}

回答by Bimal Grg

Use regular expression

使用正则表达式

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>

回答by Ellone

I 'm using this :

我正在使用这个:

function getFirstWord(str) {
        let spaceIndex = str.indexOf(' ');
        return spaceIndex === -1 ? str : str.substr(0, spaceIndex);
    };

回答by lukaserat

How about using underscorejs

如何使用 underscorejs

str = "There are so many places on earth that I want to go, i just dont have time. :("
firstWord = _.first( str.split(" ") )

回答by CPHPython

An improvement upon previous answers (working on multi-line or tabbed strings):

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

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

Orusing searchand substr:

使用searchsubstr

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

Orwithoutregex:

或者没有正则表达式:

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

Examples:

例子:

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

回答by Diego Plutino

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

回答by rAjA

This code should get you the first word,

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

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

回答by TheLastCodeBender

One of the simplest ways to do this is like this

最简单的方法之一是这样的

var totalWords = "my name is rahul.";
var firstWord = totalWords.replace(/ .*/, '');
alert(firstWord);
console.log(firstWord);

回答by Scott Sauyet

In modern JS, this is simplified, and you can write something like this:

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

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

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

console .log (firstWords (str))

We first split the string on the |and then split each string in the resulting array on any white space, keeping only the first one.

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

回答by Will

I'm surprised this method hasn't been mentioned: "Some string".split(' ').shift()

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



To answer the question directly:

直接回答问题:

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