Post

2 followers Follow
0
Avatar

Strange error using indexOf and substring

I will try explain my problem showing what works, and what not (when combining the pieces which do work), when trying to only display the first email address of a user who has more than one (a calculated value that comes from a different app).

Code:

var emailstring= @email address+"";

emailstring.substring(0,99)

Preview: albert@reson.co.za,albert@gmail.com

Okay, so the above shows you what the variable value is (or the first 99 characters at least).

 

Code:

var emailstring= @email address+"";

emailstring.indexOf(",")

Preview: 18.0

Okay, so the indexOf function finds the comma in the string and reports its position as correctly as 18.0 

 

Code:

var emailstring= @email address+"";

emailstring.substring(0,18.0)

Preview: albert@reson.co.za

Okay, so using a value of 18.0 (manually in the code), correctly trims off the comma and second email adres from the string and shows the desired outcome

BUT, here comes the problem I can't seem to solve:

When I now use the above separate functions together to find the position of the comma and only produce the first email adres, it gives an error:

Code:

var emailstring= @email address+"";

emailstring.substring(0,emailstring.indexOf(","))

Preview: Invalid value "albert@reson.co.za" (string): must be a number

 

So what is wrong here? 

I really hope someone can shed some light on this.

Paul Naudé

Please sign in to leave a comment.

2 comments

1
Avatar

Hi Paul,

ignore that error notification. It's a bit complicated to explain what happens in the background. The preview is generated by the Sandbox and if specific JS methods or combinations of methods appear in your code the Sandbox expects other result format (here: a number instead of a string). In other words: The Sandbox is over-sensitive. Ignore it and save the template. 

Btw: You don't need substring and indexOf for what you want to do:

@email address.split(",")[0] returns the first email address.

@email address.split(",")[1] returns the second email address.

I assume @email address is a text field in the same app?

Rainer

Rainer Grabowski 1 vote
0
Avatar

Thanks Rainer, that kept me scratching my head for hours.

I like your suggestion, much easier to implement.

Regards

Paul Naudé 0 votes