Robert Samarji
Robert Samarji

Reputation: 113

Remove characters in String that appear after specific character

In Google Apps Script, I'm attempting to remove all characters from a string that appear after a specific character.

When I perform Logger.log(data) I get this:

[17-12-14 19:31:55:251 GMT] 
[17-12-14 19:31:55:252 GMT] ID
[17-12-14 19:31:55:253 GMT] 11111||q467jeX
[17-12-14 19:31:55:254 GMT] undefined
[17-12-14 19:31:55:255 GMT] 
[17-12-14 19:31:55:256 GMT] ID
[17-12-14 19:31:55:257 GMT] undefined
[17-12-14 19:31:55:258 GMT] 22222||K6OmenP
[17-12-14 19:31:55:259 GMT] 

I would like to remove all characters that come after "|", so that "data" looks like:

[17-12-14 19:31:55:251 GMT] 
[17-12-14 19:31:55:252 GMT] ID
[17-12-14 19:31:55:253 GMT] 11111
[17-12-14 19:31:55:254 GMT] undefined
[17-12-14 19:31:55:255 GMT] 
[17-12-14 19:31:55:256 GMT] ID
[17-12-14 19:31:55:257 GMT] undefined
[17-12-14 19:31:55:258 GMT] 22222
[17-12-14 19:31:55:259 GMT] 

I've tried using .split, .map and .subString methods, but I must be doing something wrong. Does anyone know the best way to do this?

Upvotes: 0

Views: 1988

Answers (4)

Umair Mohammad
Umair Mohammad

Reputation: 4635

You must be doing console.log(str) or Logger.log(str)

So try just replacing that str with String(str).subString(0, String(str).indexOf('|'))

Thanks.

Upvotes: 0

Ritesh Nair
Ritesh Nair

Reputation: 3355

You can use JavaScript String split() Method

var text = "22222||K6OmenP";
var data = text.split("|")[0];
Logger.log(data);

Upvotes: 2

JJWesterkamp
JJWesterkamp

Reputation: 7916

If this is a string in Javascript (the question is tagged javascript) you should be able to achieve your wanted result with a simple regex:

const subject = `[17-12-14 19:31:55:251 GMT] 
[17-12-14 19:31:55:252 GMT] ID
[17-12-14 19:31:55:253 GMT] 11111||q467jeX
[17-12-14 19:31:55:254 GMT] undefined
[17-12-14 19:31:55:255 GMT] 
[17-12-14 19:31:55:256 GMT] ID
[17-12-14 19:31:55:257 GMT] undefined
[17-12-14 19:31:55:258 GMT] 22222||K6OmenP
[17-12-14 19:31:55:259 GMT]
`;

const result = subject.replace(/(\|.*)$/gm, '');

Upvotes: 0

Bill - K5WL
Bill - K5WL

Reputation: 716

.indexOf is the method you are looking for. Do a x.substring(0,x.indexOf('|'));

Upvotes: 1

Related Questions