简体   繁体   English

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

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

I want to get substring from string at last index match space and put it into another string : 我想从字符串的最后一个索引匹配空间中获取子字符串,并将其放入另一个字符串中:

for example if I have : var string1="hello any body from me"; 例如,如果我有: var string1="hello any body from me";

in string1 I have 4 spaces and I want to get the word after last spaces in string1 so here I want to get the word "me" ... I don't know number of spaces in string1 ... so How I can get substring from string after last seen to specific characer like space ? 在string1中,我有4个空格,我想在string1中的最后一个空格之后得到单词,所以在这里我想得到单词“ me” ...我不知道string1中的空格数量...所以我如何获得从最后一次看到的字符串到特定字符(如空格)的子字符串?

You could try something like this using the split method, where input is your string: 您可以使用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); 

Use split to make it an array and get the last element: 使用split使其成为数组并获取最后一个元素:

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

You can use split method to split the string by a given separator, " " in this case, and then get the final substring of the returned array. 您可以使用split方法将字符串分隔为给定的分隔符“”,在这种情况下,然后获取返回数组的最终子字符串。

This is a good method if you want to use other parts of the string and it is also easily readable: 如果您想使用字符串的其他部分,这是一个好方法,并且它也易于阅读:

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

This is a good method without the need for the rest of the substrings if you prefer to write quick and dirty: 如果您喜欢快速而又肮脏地编写,那么这是一个不需要其余子字符串的好方法:

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

Or just : 要不就 :

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

Thank's to reverse method 谢谢扭转方法

I'd use a regular expression to avoid the array overhead: 我将使用正则表达式来避免数组开销:

 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