What is LastIndexOf method and how it works?
Can't unserstand how this example work. lastIndexOf() Method
Is there a LastIndexOf in SQL Server? - Stack Overflow
Slice/lastIndexOf method in javascript
Videos
lastIndexOf returns:
the zero-based index position of the last occurrence of a specified Unicode character or string
In your example we are looking for the last \ in the path and then taking the next part in the path which is the file name.
Copyvar lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
What this does is to find the last backslash. If one exists (if (lastIndex >= 0)), then we remove everything leading up to it using substring. In other words, the code removes the path before a file name.
Edit: I'm an idiot and messed up the substring syntax. Corrected.
If you want everything after the last _, then use:
Copyselect right(db_name(), charindex('_', reverse(db_name()) + '_') - 1)
If you want everything before, then use left():
Copyselect left(db_name(), len(db_name()) - charindex('_', reverse(db_name()) + '_'))
Wrote 2 functions, 1 to return LastIndexOf for the selected character.
CopyCREATE FUNCTION dbo.LastIndexOf(@source nvarchar(80), @pattern char)
RETURNS int
BEGIN
RETURN (LEN(@source)) - CHARINDEX(@pattern, REVERSE(@source))
END;
GO
and 1 to return a string before this LastIndexOf. Maybe it will be useful to someone.
CopyCREATE FUNCTION dbo.StringBeforeLastIndex(@source nvarchar(80), @pattern char)
RETURNS nvarchar(80)
BEGIN
DECLARE @lastIndex int
SET @lastIndex = (LEN(@source)) - CHARINDEX(@pattern, REVERSE(@source))
RETURN SUBSTRING(@source, 0, @lastindex + 1)
-- +1 because index starts at 0, but length at 1, so to get up to 11th index, we need LENGTH 11+1=12
END;
GO