# Scripted Field: getting first index of a substring

**URL:** <https://discuss.elastic.co/t/scripted-field-getting-first-index-of-a-substring/81418>\
**Category:** Kibana\
**Created:** [April 6, 2017, 6:29am UTC](https://discuss.elastic.co/t/scripted-field-getting-first-index-of-a-substring/81418 "2017-04-06T06:29:15Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![Joe\_Fleming](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/joe_fleming/32/3561_2.png) [@Joe\_Fleming](https://discuss.elastic.co/u/Joe_Fleming)\
**Post date:** [April 6, 2017, 7:45pm UTC](https://discuss.elastic.co/t/scripted-field-getting-first-index-of-a-substring/81418/2 "2017-04-06T19:45:19Z")

</div>

I'm not a painless expert, but [here is the API](https://www.elastic.co/guide/en/elasticsearch/reference/current/painless-api-reference.html).

You already know the index of the last / from the use of `lastIndexOf`, and you're already using substring. If you give [substring](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring%2Dint%2Dint%2D) 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);`

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

```

---

_[View the full topic](https://discuss.elastic.co/t/scripted-field-getting-first-index-of-a-substring/81418)._
