user1935987
user1935987

Reputation: 3347

JavaScript get the last character's position of the string inside the other string

i guess the problem is extremely casual, but can't really find the solution.

i have a string

var full = 'hopaopGmailb3GkI'
var name = 'hopaop'
var service = 'Gmail'

How do i get the b3GkI from the original string, suppose the name and service are dynamic values also parsed from the string var full.

Or how to get the index of the last character of the variable service inside of the var full string

I need to get the index of the last character of the variable service inside of the var full string. var index = full.indexOf(service); returning the first character's index (6 in this example). Also for some reason i can't exclude name + service from the string.

Upvotes: 0

Views: 453

Answers (3)

bdimag
bdimag

Reputation: 963

Another alternative with Regular Expressions

var full = 'hopaopGmailb3GkI';
var service = 'Gmail';

console.log((function(source, service) {
    var match = new RegExp('(.+)' + service + '(.+)').exec(source);
    return {
        'service': service,
        'name': match[1],
        'token': match[2]
    };
})(full, service));

Returns an object like {"service":"Gmail","name":"hopaop","token":"b3GkI"}

Upvotes: 1

Vladu Ionut
Vladu Ionut

Reputation: 8183

Version 1

var full = 'hopaopGmailb3GkI';
var name = 'hopaop';
var service = 'Gmail';
var result = full.substring(full.indexOf(service) + service.length)
console.log(result);

Version 2

you can use Split

var full = 'hopaopGmailb3GkI';
var name = 'hopaop';
var service = 'Gmail';
var result = full.split(service)[1];
console.log(result);

Upvotes: 1

DabaloSe7eN
DabaloSe7eN

Reputation: 169

var index = full.indexOf(service) + service.length; should do the trick. I also feel like you can come up with a regular expression to accomplish this, but I am no master.

Upvotes: 2

Related Questions