在Google Apps脚本中,我尝试删除特定字符后出现的字符串中的所有字符。
当我执行Logger.log(数据)时,我得到了这个:
[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]
我想删除" |"之后的所有字符,以便"数据"看起来像:
[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]
我尝试过使用.split,.map和.subString方法,但我一定做错了。有谁知道最好的方法吗?
答案 0 :(得分:2)
您可以使用JavaScript String split() Method
var text = "22222||K6OmenP";
var data = text.split("|")[0];
Logger.log(data);
答案 1 :(得分:0)
.indexOf是您正在寻找的方法。做一个x.substring(0,x.indexOf('|'));
答案 2 :(得分:0)
如果这是Javascript中的字符串(问题标记为javascript),您应该能够使用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, '');
答案 3 :(得分:0)
您必须执行console.log(str)
或Logger.log(str)
因此,请尝试将str
替换为String(str).subString(0, String(str).indexOf('|'))
感谢。