Skip to content

substr - Pull a substring from a string

The substr function takes a string and a position and, optionally, a length, and produces a substring from it. It is especially useful for simple value extraction that doesn't warrant regex capture groups.

Syntax

Like many functions in DataPrime, substr supports two notations, function and method notation. These interchangeable forms allow flexibility in how you structure expressions.

substr(value: string, from: number, length: number?): string
value: string.substr(from: number, length: number?): string

Arguments

NameTypeRequiredDescription
valuestringtrueThe main string
fromnumbertrueThe index from which we should capture the substring
lengthnumberfalseThe number of characters we should capture after from. Defaults to the remainder of the string.

Example - Using substring to grab a value at the end of a string

Before we can decide how much of a string we want to pull out, we first need to work out our index. indexOf is perfect for this. Consider this document:

{
    "msg": "result=Some value"
}

We want to get just the value, so we can use indexOf to work out the position of =:

create index_of_value from (msg.indexOf('=') + 1) # Convert to base 1

Now we have our index, we're able to take our substring:

create value from substr(msg, index_of_value + 1)
create value from msg.substr(index_of_value + 1)

This will pull everything from the position after the =, to the end of the string, resulting in the following document:

{
    "msg": "result=Some value",
    "index_of_value": 7,
    "value": "Some value"
}