# 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:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![vishalkin](https://avatars.discourse-cdn.com/v4/letter/v/ccd318/32.png) [@vishalkin](https://discuss.elastic.co/u/vishalkin)\
**Post date:** [April 6, 2017, 6:29am UTC](https://discuss.elastic.co/t/scripted-field-getting-first-index-of-a-substring/81418/1 "2017-04-06T06:29:15Z")

</div>

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 "";

---

<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 "";

```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [May 4, 2017, 7:45pm UTC](https://discuss.elastic.co/t/scripted-field-getting-first-index-of-a-substring/81418/3 "2017-05-04T19:45:24Z")

</div>

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