繁体   English   中英

javascript-如何从最后一次看到特定字符后的字符串中获取子字符串?

[英]How to get substring from string after last seen to specific characer in javascript?

我想从字符串的最后一个索引匹配空间中获取子字符串,并将其放入另一个字符串中:

例如,如果我有: var string1="hello any body from me";

在string1中,我有4个空格,我想在string1中的最后一个空格之后得到单词,所以在这里我想得到单词“ me” ...我不知道string1中的空格数量...所以我如何获得从最后一次看到的字符串到特定字符(如空格)的子字符串?

您可以使用split方法尝试这样的操作,其中input是您的字符串:

var splitted = input.split(' ');
var s = splitted[splitted.length-1];

 var splitted = "hello any body from me".split(' '); var s = splitted[splitted.length-1]; console.log(s); 

使用split使其成为数组并获取最后一个元素:

var arr = st.split(" "); // where string1 is st
var result = arr[arr.length-1];
console.log(result);

您可以使用split方法将字符串分隔为给定的分隔符“”,在这种情况下,然后获取返回数组的最终子字符串。

如果您想使用字符串的其他部分,这是一个好方法,并且它也易于阅读:

 // setup your string var string1 = "hello any body from me"; // split your string into an array of substrings with the " " separator var splitString = string1.split(" "); // get the last substring from the array var lastSubstr = splitString[splitString.length - 1]; // this will log "me" console.log(lastSubstr); // ... // oh i now actually also need the first part of the string // i still have my splitString variable so i can use this again! // this will log "hello" console.log(splitString[0]); 

如果您喜欢快速而又肮脏地编写,那么这是一个不需要其余子字符串的好方法:

 // setup your string var string1 = "hello any body from me"; // split your string into an array of substrings with the " " separator, reverse it, and then select the first substring var lastSubstr = string1.split(" ").reverse()[0]; // this will log "me" console.log(lastSubstr); 

要不就 :

var string1 = "hello any body from me";
var result = string1.split(" ").reverse()[0];
console.log(result); // me

谢谢扭转方法

我将使用正则表达式来避免数组开销:

 var string1 = "hello any body from me"; var matches = /\\s(\\S*)$/.exec(string1); if (matches) console.log(matches[1]); 

暂无
暂无

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

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