简体   繁体   English

Javascript:返回字符串中的最后一个单词

[英]Javascript: Returning the last word in a string

right to it:对它的权利:

I have a words string which has two words in it, and i need to return the last word.我有一个words字符串,其中有两个单词,我需要返回最后一个单词。 They are seperated by a " ".它们由“”分隔。 How do i do this?我该怎么做呢?

function test(words) {

var n = words.indexOf(" ");
var res = words.substring(n+1,-1);
return res;

}

I've been told to use indexOf and substring but it's not required.我被告知要使用indexOfsubstring ,但这不是必需的。 Anyone have an easy way to do this?任何人都有一个简单的方法来做到这一点? (with or without indexOf and substring ) (有或没有indexOfsubstring

Try this:试试这个:

you can use words with n word length.您可以使用 n 字长的单词。

example:例子:

  words = "Hello World";
  words = "One Hello World";
  words = "Two Hello World";
  words = "Three Hello World";

All will return same value: "World"所有将返回相同的值:“世界”

function test(words) {
    var n = words.split(" ");
    return n[n.length - 1];

}

You could also:您还可以:

words.split(" ").pop();

Just chaining the result (array) of the split function and popping the last element would do the trick in just one line :)只需链接 split 函数的结果(数组)并弹出最后一个元素就可以在一行中完成:)

var data = "Welcome to Stack Overflow";
console.log(data.split(" ").splice(-1));

Output输出

[ 'Overflow' ]

This works even if there is no space in the original string, so you can straight away get the element like this即使原始字符串中没有空格,这也有效,因此您可以立即获得这样的元素

var data = "WelcometoStackOverflow";
console.log(data.split(" ").splice(-1)[0]);

Output输出

WelcometoStackOverflow

You want the last word , which suggests lastIndexOf may be more efficient for you than indexOf .你想要最后一个词,这表明lastIndexOf对你来说可能比indexOf更有效。 Further, slice is also a method available to Strings .此外, slice也是Strings可用的方法。

var str = 'foo bar fizz buzz';
str.slice(
    str.lastIndexOf(' ') + 1
); // "buzz"

See this jsperf from 2011 showing the split vs indexOf + slice vs indexOf + substring and this perf which shows lastIndexOf is about the same efficiency as indexOf , it mostly depends on how long until the match happens.请参阅 2011 年的这个 jsperf显示split vs indexOf + slice vs indexOf + substring这个显示lastIndexOf的性能与indexOf大致相同,它主要取决于匹配发生多长时间。

To complete Jyoti Prakash, you could add multiple separators ( \\s | , ) to split your string (via this post )要完成 Jyoti Prakash,您可以添加多个分隔符 ( \\s | , ) 来拆分您的字符串(通过这篇文章

Example:例子:

function lastWord(words) {
  var n = words.split(/[\s,]+/) ;
  return n[n.length - 1];
}

Note: regex \\s means whitespace characters : A space character, A tab character, A carriage return character, A new line character, A vertical tab character, A form feed character注意:正则表达式\\s表示空白字符:空格字符、制表符、回车符、换行符、垂直制表符、换页符

snippet片段

 var wordsA = "Hello Worlda"; // tab var wordsB = "One Hello\\nWorldb"; var wordsC = "Two,Hello,Worldc"; var wordsD = "Three Hello Worldd"; function lastWord(words) { var n = words.split(/[\\s,]+/); return n[n.length - 1]; } $('#A').html( lastWord(wordsA) ); $('#B').html( lastWord(wordsB) ); $('#C').html( lastWord(wordsC) ); $('#D').html( lastWord(wordsD) );
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> A:<span id="A"></span><br/> B:<span id="B"></span><br/> C:<span id="C"></span><br/> D:<span id="D"></span><br/>

Adding from the accepted answer, if the input string is "Hello World " (note the extra space at the end), it will return '' .从接受的答案中添加,如果输入字符串是"Hello World " (注意末尾的额外空格),它将返回'' The code below should anticipate in case user fat-fingered " " :下面的代码应该预料到用户胖手指的情况" "

var lastWord= function(str) {
  if (str.trim() === ""){
    return 0;
  } else {   
    var splitStr = str.split(' ');
    splitStr = splitStr.filter(lengthFilter);
    return splitStr[splitStr.length - 1];
  }
};

var lengthFilter = function(str){
    return str.length >= 1;
};

Easiest way is to use slice method:-最简单的方法是使用切片方法:-

For example:-例如:-

let words = "hello world";
let res = words.slice(6,13);
console.log(res);
/**
 * Get last word from a text
 * @param {!string} text
 * @return {!string}
 */
function getLastWord(text) {
  return text
    .split(new RegExp("[" + RegExp.quote(wordDelimiters + sentenceDelimiters) + "]+"))
    .filter(x => !!x)
    .slice(-1)
    .join(" ");
}

According to me the easiest way is:在我看来,最简单的方法是:

lastName.trim().split(" ").slice(-1)

Use split()使用split()

function lastword(words){
 array = words.split(' ');

 return array[1]
}

Its pretty straight forward.它非常简单。 You have got two words separated by space.你有两个用空格分隔的单词。 Lets break the string into array using split() method.让我们使用 split() 方法将字符串分解为数组。 Now your array has two elements with indices 0 and 1. Alert the element with index 1.现在您的数组有两个索引为 0 和 1 的元素。警告索引为 1 的元素。

var str="abc def";
var arr=str.split(" ");
alert(arr[1]);

暂无
暂无

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

相关问题 Javascript / jQuery - 替换字符串中单词的最后一次出现 - Javascript/jQuery - replace last occurence of a word in a string 如何使用 JavaScript 删除字符串中的最后一个单词 - How to remove the last word in a string using JavaScript 如何获取 JavaScript 中单词或字符串的最后一个字母? - How to get the last letter of a word or string in JavaScript? 如何使用 JavaScript 正则表达式提取字符串中的最后一个单词? - How to extract the last word in a string with a JavaScript regex? 在对最后一个字不起作用的字符串javascript代码中查找最长的单词 - Finding longest word in a string javascript code that is not working on the last wordd 使用 node js / javascript 替换字符串的最后一个单词 - replacing last word of string using node js / javascript 使用 javascript 交换字符串中每个单词的第一个和最后一个字母 - swapping the first and last letters of every word in a string using javascript Javascript-查找单词在字符串中特定出现的位置(不是开头或结尾) - Javascript - Find position of specific occurrence of a word in a string (not first or last) Javascript / jquery - 从字符串中获取第一个和最后一个单词然后用类包装 - Javascript / jquery - Grab first and last word from string then wrap with class Javascript 和正则表达式:删除字符串中最后一个单词后的空格 - Javascript and regex: remove space after the last word in a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM