Scripted Field: getting first index of a substring

Hi. I have a following string field
string_value.keyword
The following code gives the last part that comes after / (slash).
How can I get only the first part that comes before /?

def path = doc['string_value.keyword'].value;
if (path != null) {
int lastSlashIndex = path.lastIndexOf('/');
if (lastSlashIndex > 0) {
return path.substring(lastSlashIndex+1);
}
}
return "";

I'm not a painless expert, but here is the API.

You already know the index of the last / from the use of lastIndexOf, and you're already using substring. If you give substring 2 arguments, it'll use the first one as the start and the last one as the end, non-inclusive.

So, in your case, this should give you the content before the last / - return path.substring(0, lastSlashIndex);

def path = doc['string_value.keyword'].value;
if (path != null) {
int lastSlashIndex = path.lastIndexOf('/');
if (lastSlashIndex > 0) {
return path.substring(0, lastSlashIndex);
}
}
return "";
1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.