Skip to main content
sd0123
Known Participant
April 23, 2020
Answered

Split String to Extract First Word from Text field

  • April 23, 2020
  • 1 reply
  • 2812 views

I would like to split a text field, named Client1, to extract just the first word using a space as the delimiter.

 

Here is what I've put together from reasearch, but it isn't working when placed as a custom calculation script in a read only text field:

 

var str1 = this.getField("Client1").value;
var res1 = str1.split(" ", 1);

event.value = res1

 

I think I'm missing something in going from the array produced by var res1 to the desired event.value for the field. I appreciate a point in the right direction - thanks!

This topic has been closed for replies.
Correct answer try67

Hiii!  It's a full name field and I want to extract the first name - so there is the possibility of the field being more than two words - so just use this?

 

var str1 = this.getField("Client1").value;
var res1 = str1.split(" ");

var first = res1[0];

event.value = first;

 


I suspected it was a name field... In that case I would recommend you don't do that, as you can't know how long the actual first name is (many people have multiple words in their names, both first and last, not to mention middle names, titles, etc.). Let the user enter their own name. If you want to make things a bit more automated then do it the other way around: Let the user enter their first and last names separately and then combine them automatically to a "Full Name" field.

1 reply

sd0123
sd0123Author
Known Participant
April 23, 2020

I think I got it to work with this:

 

var str1 = this.getField("Client1").value;
var res1 = str1.split(" ");

if (res1.length==2){
var first = res1[0];
var last = res1[1];

event.value = first;
}

try67
Community Expert
Community Expert
April 23, 2020

If the value of this field will be more (or less!) than two words your script won't work.

You should remove that if-condition.

sd0123
sd0123Author
Known Participant
April 24, 2020

Hiii!  It's a full name field and I want to extract the first name - so there is the possibility of the field being more than two words - so just use this?

 

var str1 = this.getField("Client1").value;
var res1 = str1.split(" ");

var first = res1[0];

event.value = first;