Skip to Content
Technical Articles

Working with String Functions

Quite often during coding we need to manipulate strings. We may need to extract some text from a string or pad a number with zeroes. In this blog, I will demonstrate some examples of these string functions in Analytic Designer.

Extract the Time Portion of a Date/Time String

In our first example, we want to extract the time portion of the date/time string:

20201231 11:56:35

Our first task is to locate the space that is positioned between the date and the time. This space is also known as a delimiter. Delimiters can be spaces, or and other character that somebody has decided to use. Common delimiters are spaces, /, -, semicolons, ~, and a few more. In this exercise, we will use space.

In our code we will assign our date/time value to a string. In other code, we may have retrieved it from a table or had it inputted through a prompt.

var strDateTime = “20201231 11:56:35”;

To find the position of the space, we use the following formula:

var intSpacePlace = strDateTime.indexOf(” “);

In this formula, we use the indexOf() method (function) of the strDateTime variable. To access this, and other functions, simply type a period after the variable, and then press [CTRL]+Space. A pop up list of available functions for the variable will be displayed. Then, select the indexOf() from the list.

The pop-up menu will also give descriptions for selected methods and properties. For indexOf function, the help displays that it will return the index of the first occurrence of the argument passed to it, as shown above.

After selecting the indexOf function, we can see what arguments the indexOf function expects and what type of value that it will return. We see that it expects two arguments: searchValue and fromIndex, and it will return a value of type number. Sometimes, the function does not need both arguments, which is the case here. We only need to define the searchValue . If we wanted to start searching somewhere other than the beginning of the string, then we can use fromValue to define a starting position within the string.

In our line of code to find the space: var intSpacePlace = strDateTime.indexOf(” “); we are passing the argument ” “, because we only have a single space in the date/time string. The code will store the position of the space in the variable intSpacePlace.

Once we have the space position, we can output the position to the console to make sure that the value is reasonable. Most coders will this, even though it seems obvious what the value is, because it is better to find issues early in the code. We will use to following code to output to the console:

console.log(“position of space in date/time string: ” + intSpacePlace.toString());

Note: Notice the toString method that we are using at the end of our intSpacePlace variable. We need this method to convert the number to text, so that we can concatenate the variable value to the label string.

The output in the console will be:

position of space in date/time string: 8

Note: To access the console, first run the Analytic Application. Then, in Chrome press the F12 key, which will open a code specific area in the browser. Then, click on the Console menu item. You will see some output that we did not send, but at the bottom you should see our output.

Now that we got the position of the space, we can extract the time using the subString method, as shown below:

strDateTime.subString(intSpacePlace)

Using the console.log function to display the result:

Code: console.log(“time with leading space: ” + strDateTime.substring(intSpacePlace));

console output: time with leading space: 11:56:35

When we output the time that we have extracted, we may realize that we have included a leading space: ‘ 11:56:35’. The space is there, because we started the extraction at the space and not at the beginning of the time. We can start at the beginning of time by simply adding a one to the value of intSpacePlace, as in the following:

Code:
intSpacePlace = intSpacePlace + 1;
console.log(“time with no leading space: ” + strDateTime.substring(intSpacePlace));

Output:
time with no leading space: 11:56:35

We were able to start at the time value, because we knew that there was only one space before the time value. If we were not sure how many spaces that there were, we could use the trim function without adding a one to the intSpacePlace value.

Code:
var strTimeWithSpace = strDateTime.substring(strDateTime.indexOf(” “));
console.log(“time with leading space trimmed: ” + strTimeWithSpace.trim());

Output:
time with no leading space: 11:56:35

Using the subString method of a string variable will allow us to easily extract ending text from the string value, if we know the starting position of the text within the string. We can use the indexOf method to locate the text in the string, if we know a common delimiter that denotes where the text will start. Lastly, the trim method will remove both leading and ending spaces form a string.

Below is a complete list of this code:

// Date string with space //
// Want to extract time
//--------------------------------------------------------------------------//
console.log("// Want to extract time");
console.log("// 20201231 11:56:35");

var strDateTime = "20201231 11:56:35";
// Three step solution -------------------------------------
// Locate the space
var intSpacePlace = strDateTime.indexOf(" ");
console.log("position of space in date/time string: " + intSpacePlace.toString());
// Extract time, but with leading space
console.log("time with leading space: " + strDateTime.substring(intSpacePlace));

// Eliminate space by adding one to space position
intSpacePlace = intSpacePlace + 1;
// Use subString to retrieve time with no space
console.log("time with no leading space: " + strDateTime.substring(intSpacePlace));

// Could do it in one line---------------------------------- 
console.log("time with no leading space: " + strDateTime.substring(strDateTime.indexOf(" ")+1));

// Instead of adding 1 to get to space after ---------------
// Could use Trim instead
var strTimeWithSpace = strDateTime.substring(strDateTime.indexOf(" "));
console.log("time with leading space trimmed: " + strTimeWithSpace.trim());
console.log("");
//--------------------------------------------------------------------------//

Extract Text Embedded in a String

What if now the text that we want to extract is embedded in a string? In this section, we will explore how to extract embedded text. For this example, we will assign the following variable:

var strEmbedded = “The red ball”;

We want to extract the color of the ball. To start, we will again find index position of the first space, which is before the color in the string. To do this, we will use the the following code:

Code: var intColorPos = strEmbedded.indexOf(” “);
console.log(“Space before color position: ” + intColorPos.toString());

Output: Space before color position: 3

This shows us that the starting position of the space is three. It is three, because the first character of the string is at position 0. In the previous example, we simply used this starting value in the subString function. However, in this example, we also need the end position of the color within the string. To find this position, we will locate the last space in the string, which is right after the color.

Code: var intColorEnd = strEmbedded.lastIndexOf(” “);
console.log(“Space after color position: ” + intColorEnd.toString());

Output: Space after color position: 7

The lastIndexOf will return the last time the text appears in a string. Now, we know that the space before is 3, and the space after is 7. The length of the color with the spaces is 7-3, or 4. We will now use the subStr function to extract the color:

Code:
var strColorWithSpace = strEmbedded.substr(intColorPos, intColorEnd-intColorPos);
console.log(“The color is (no space management): ” + strColorWithSpace);

var strNoSpace = strEmbedded.substr(intColorPos, intColorEnd-intColorPos).trim();
console.log(“The color is (with space management): ” + strNoSpace );

Output:
The color is (no space management):  red
The color is (with space management): red

Notice that we used the trim method to eliminate the space, because the length of the color is actually 3, not four as out 7-3 formula yielded.

We have used both the subStr and subString functions. Both of these functions will extract text from a string, but they take slightly different arguments.

The subStr function uses starting position and length, as in the following:

// subStr uses start and length
// intColorPos is start
// intColorEnd-intColorPos is length
console.log(“subStr: ” + strEmbedded.substr(intColorPos,intColorEnd-intColorPos));

The subString uses starting position and end position, as in the following:

// subString uses start and end
// intColorPos is start
// intColorEnd is end
console.log(“subString: ” + strEmbedded.substring(intColorPos, intColorEnd));

In this example, we not only needed to know the starting position of the text to extract, we also needed to know the ending position. The string for this example was rather structured, because we knew that the color was the middle word in the string.

Below is a complete listing of the code:

// Embedded text //
//--------------------------------------------------------------------------//
console.log("// Want to extract embedded color");
console.log("// The red ball");

var strEmbedded = "The red ball";

// Want to extract the color of the ball
// Find position of color
var intColorPos = strEmbedded.indexOf(" ");
console.log("Space before color position: " + intColorPos.toString());
// Find Length of color
var intColorEnd = strEmbedded.lastIndexOf(" ");
console.log("Space after color position: " + intColorEnd.toString());
// isolate color with spaces
var strColorWithSpace = strEmbedded.substr(intColorPos, intColorEnd-intColorPos);
console.log("The color is (no space management): " + strColorWithSpace);
// isolate color with no spaces
var strNoSpace = strEmbedded.substr(intColorPos, intColorEnd-intColorPos).trim();
console.log("The color is (with space management): " + strNoSpace );

// subStr uses start and length
// intColorPos is start
// intColorEnd-intColorPos is length
console.log("subStr: " + strEmbedded.substr(intColorPos,intColorEnd-intColorPos));

// subString uses start and end
// intColorPos is start
// intColorEnd is end
console.log("subString: " + strEmbedded.substring(intColorPos, intColorEnd));
console.log("");

Extract Deeply Embedded Text identified by a delimiter within a String

In this example, we are going to extract text identifying the color from a string. However, in this string the color can appear at any position within the string. We will use the following string:

var strDescLine = “Diameter: 15 cm; Color: blue; Weight: 15 kg”;

Here the color is one of many descriptors, and the descriptors have identifying delimiters. For the case of color, the descriptor is Color:. This example will be similar to the previous example, but we will not know the number of spaces before, or after, the color in the string. Therefore, we will not use space as the delimiter. Instead, we will use color:, as in the following:

var strDelimiter = “color: “;

We will also need to know the length of the delimiter, so we will use the following to get the length:

var intDelimiterLength = strDelimiter.length;

Now that we have the delimiter defined and know the length of the delimiter, let’s locate the delimiter within the string with the following code:

Code:
var intDelimiterPos = strDelimiter.indexOf(strDelimiter);
console.log(“Doesn’t find delimiter (different case): ” + intDelimiterPos.toString());

Output:
Doesn’t find delimiter (different case): 0

The indexOf function failed to locate the delimiter, because the case in the string differs from the case that we assigned our variable (“color: ” <> “Color: “). We could change the case of the value in our variable, but what if the case in the string changes. We cannot depend on the case in the string to be constant. So we will convert the entire string to lower case font, as in the following:

Code: var strDescLineLC = strDescLine.toLowerCase();
console.log(“lower case string: ” + strDescLineLC);

Output: lower case string: diameter: 15 cm; color: blue; weight: 15 kg

Now, lets try to find the delimiter again:

Code: intDelimiterPos = strDescLineLC.indexOf(strDelimiter);
console.log(“delimiter position: ” + intDelimiterPos.toString());

Output: delimiter position: 17

Now, the code returns the starting position as 17. In this example, we are not going to extract the color in one step. We will first extract the text in the sub-string beginning with the color, as in the following:

Code:
var strStartWithColor = strDescLineLC.substring(intDelimiterPos+intDelimiterLength);
console.log(“string starting with color: ” + strStartWithColor);

Output:
string starting with color: blue; weight: 15 kg

We were able to start at the beginning of the color, because we use start plus length to determine where the color started (intDelimiterPos+intDelimiterLength). Now the final step is to extract the color, as in the following code:

Code:
var strEmbeddedColor = strStartWithColor.substring(0, strStartWithColor.indexOf(“;”));
console.log(“color is: ” + strEmbeddedColor );

Output:
color is: blue

I used a few lines of code to extract the color. However, I could have done it in fewer as in the following:

Code:
var strOneLiner = strDescLineLC.substring(strDescLineLC.indexOf(strDelimiter)+strDelimiter.length, strDescLineLC.indexOf(“;”, strDescLineLC.indexOf(strDelimiter)+strDelimiter.length));

Output:
One line of code: blue

Note: Many coders will break code down into several lines or assignments, so that the code is easier to read, maintain and modify.

Now we have seen how to extract text at the end of a string, embedded in  a string, and deeply embedded in a string. We used the indexOf, lastIndexOf, subStr, and subString methods of the string object to accomplish the extractions.

Below is the code for this section:

// Deeply embedded text //
//--------------------------------------------------------------------------//
console.log("// Want to extract deeply embedded color");
console.log("// Diameter: 15 cm; Color: blue; Weight: 15 kg");

var strDescLine = "Diameter: 15 cm; Color: blue; Weight: 15 kg";

// Want to extract the color of the ball
// Find position of color
var strDelimiter = "color: ";
var intDelimiterLength = strDelimiter.length;
var intDelimiterPos = strDelimiter.indexOf(strDelimiter);
// Doesn't find dimimiter, because color: <> Color:
console.log("Doesn't find delimiter (different case): " + intDelimiterPos.toString());

// Convert to common case
var strDescLineLC = strDescLine.toLowerCase();
console.log("lower case string: " + strDescLineLC);
// Find position of color
intDelimiterPos = strDescLineLC.indexOf(strDelimiter);
// finds dimimiter, because color: = color:
console.log("delimiter position: " + intDelimiterPos.toString());
// Extract string starting with color
var strStartWithColor = strDescLineLC.substring(intDelimiterPos+intDelimiterLength);
console.log("string starting with color: " + strStartWithColor);
// Extract color
var strEmbeddedColor = strStartWithColor.substring(0, strStartWithColor.indexOf(";"));
console.log("color is: " + strEmbeddedColor );

// One line solution
var strOneLiner = strDescLineLC.substring(strDescLineLC.indexOf(strDelimiter)+strDelimiter.length, strDescLineLC.indexOf(";", strDescLineLC.indexOf(strDelimiter)+strDelimiter.length));
console.log("One line of code: " + strOneLiner);

Padding Numbers

As the last topic of this blog entry, I want to discuss how to pad numbers. In this example, we will left pad numbers with an X until the length is four. We will start with the following assignments:

Code: var intNumbersToPad = [“1”, “12”, “123”, “1234”];
var strX = “X”;
for(var i = 0; i<4; i++){
console.log(intNumbersToPad[i]);}

Output: 1
12
123
1234

We want the total length of our padded numbers to be four. So, for 1, we want XXX1. For 12, we want XX12. For 123, we want X123, and for 1234, we want 1234.

To repeat the X’s, we will use the repeat method of a string. To determine how many times to repeat, we will subtract the number length from 4. For example, for 1, we want to repeat 4 -1 times. For 1234, we do not want any X’s.

To do this, we will use the following code:

Code:
for (i=0; i<4; i++){
console.log(strX.repeat(4-intNumbersToPad[i].length) + intNumbersToPad[i]);}

Output: XXX1
XX12
X123
1234

Sometimes, we want all numbers to be padded  to the same length. This is a quick and convenient way to achieve this. Below is the code:

// Pad with X's //
//--------------------------------------------------------------------------//
var intNumbersToPad = ["1", "12", "123", "1234"];
var strX = "X";

console.log("// Want to pad to four places using X");
for(var i = 0; i<4; i++){
   console.log(intNumbersToPad[i]);}

// Padded output
for (i=0; i<4; i++){
   console.log(strX.repeat(4-intNumbersToPad[i].length) + intNumbersToPad[i]);}

When working with text, we often need to manipulate that text. If we can extract and pad text, then we will be much better at creating dashboards and formatted output. Please leave your comments, especially if you would like me to explore more functions. Thank you.

Be the first to leave a comment
You must be Logged on to comment or reply to a post.