Reputation: 223
How I can get the value after last char(. ; + _ etc.): e.g.
string.name+org.com
I want to get "com". Is there any function in jQuery?
Upvotes: 8
Views: 13766
Reputation: 700342
Use lastIndexOf
and substr
to find the character and get the part of the string after it:
var extension = name.substr(name.lastIndexOf(".") + 1);
Demo: http://jsfiddle.net/Guffa/K3BWn/
Upvotes: 23
Reputation: 626845
A simple and readable approch to get the substring after the last occurrence of a character from a defined set is to split the string with a regular expression containing a character class and then use pop()
to get the last element of the resulting array:
The
pop()
method removes the last element from an array and returns that element.
See a JS demo below:
var s = 'string.name+org.com';
var result = s.split(/[.;+_]/).pop();
console.log(result);
to split at all non-overlapping occurrences of the regex by default.
NOTE: If you need to match ^
, ]
, \
or -
, you may escape them and use anywhere inside the character class (e.g. /[\^\-\]\\]/
). It is possible to avoid escaping ^
(if you do not put it right after the opening [
), -
(if it is right after the opening [
, right before the closing ]
, after a valid range, or between a shorthand character class and another symbol): /[-^\]\\]/
.
Also, if you need to split with a single char, no regex is necessary:
// Get the substring after the last dot
var result = 'string.name+org.com'.split('.').pop();
console.log(result);
Upvotes: 5
Reputation: 884
maybe this is too late to consider, this codes works fine for me using jquery
var afterDot = value.substr(value.lastIndexOf('_') + 1);
You could just replate '_' to '.'
var myString = 'asd/f/df/xc/asd/test.jpg'
var parts = myString.split('/');
var answer = parts[parts.length - 1];
console.log(answer);
Upvotes: 0
Reputation: 11822
I'll throw in a crazy (i.e. no RegExp) one:
var s = 'string.name+org.com';
var a = s.split('.'); //puts all sub-Strings delimited by . into an Array
var result = a[a.length-1]; //gets the last element of that Array
alert(result);
EDIT: Since the update of the question is demanding mutiple delimiters to work this is probably not the way to go. Too crazy.....
Upvotes: 1
Reputation: 1074335
Not jQuery, just JavaScript: (not since the update indicating multiple characters). As would a regular expression with a capture group containing a character class followed by an end-of-string anchor, e.g. lastIndexOf
and substring
would do it/([^.;+_]+)$/
used with RegExp#exec
or String#match
.
var match = /([^.;+_]+)$/.exec(theStringToTest),
result = match && match[1];
Upvotes: 4
Reputation: 14318
You can use RegExp Object.
Try this code:
"http://stackoverflow.com".replace(/.*\./,"");
Upvotes: 1
Reputation: 123387
var s = "string.name+org.com",
lw = s.replace(/^.+[\W]/, '');
console.log(lw) /* com */
this will also work for
string.name+org/com
string.name+org.info
Upvotes: 1