如何从JavaScript字符串中移除空字节?解决表格选中行数据数组含无效空字节的问题
解决表格行值中的空字节问题,避免Python后端解析异常
Hey, I totally get how annoying this null byte issue can be—Python’s strict about parsing these invisible special characters, and it’s easy to hit unexpected exceptions. Let’s adjust your code to filter out those \x00 bytes (and replace them with empty strings, like your pseudocode suggests) before pushing values into your inner array.
修改后的完整代码
var outer_array = [] // 遍历选中的复选框 $("tbody input[type=checkbox]:checked").each(function(index, item) { var inner_array = [] var selector = $(this).closest("tr") // 获取当前行 // 遍历行中除第一列外的单元格 selector.find("td:not(:first)").each(function() { const cellText = $(this).text().trim(); // 检测文本中是否包含空字节(\x00) if (cellText.includes('\x00')) { inner_array.push(''); // 存在空字节则推入空字符串 } else { // 保留原有的数字转换逻辑 const processedValue = $.isNumeric(cellText) ? Number(cellText) : cellText; inner_array.push(processedValue); } }) outer_array.push(inner_array) })
额外优化:过滤更多不可见控制字符
如果除了\x00之外,还有其他ASCII控制字符导致后端异常,可以用正则表达式覆盖所有这类字符:
var outer_array = [] $("tbody input[type=checkbox]:checked").each(function(index, item) { var inner_array = [] var selector = $(this).closest("tr") selector.find("td:not(:first)").each(function() { const cellText = $(this).text().trim(); // 匹配所有ASCII控制字符(含\x00、退格、换行等) const hasInvalidChars = /[\x00-\x1F\x7F]/.test(cellText); if (hasInvalidChars) { inner_array.push(''); } else { const processedValue = $.isNumeric(cellText) ? Number(cellText) : cellText; inner_array.push(processedValue); } }) outer_array.push(inner_array) })
这个正则会覆盖从\x00(空字节)到\x1F(单元分隔符)以及\x7F(删除键)的所有不可见控制字符,能更全面地避免Python解析时的异常。
内容的提问来源于stack exchange,提问作者Cheknov
相关产品推荐
相关产品推荐

