简体   繁体   中英

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

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 ?

You could try something like this using the split method, where input is your string:

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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