sara
sara

Reputation: 168

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 ?

Upvotes: 0

Views: 69

Answers (5)

cnorthfield
cnorthfield

Reputation: 3501

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

Upvotes: 1

GOTO 0
GOTO 0

Reputation: 47642

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

Upvotes: 1

kevin ternet
kevin ternet

Reputation: 4612

Or just :

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

Thank's to reverse method

Upvotes: 1

Oluwafemi
Oluwafemi

Reputation: 14889

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

Upvotes: 1

Christos
Christos

Reputation: 53958

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

Upvotes: 1

Related Questions