JavaScript indexOf() 方法

本文介绍了 JavaScript 中的 indexOf() 方法,详细解释了如何使用此方法查找一个字符串在另一个字符串中首次出现的位置。包括方法的定义、语法、参数及返回值等,并通过实例展示了其具体应用。
http://www.w3school.com.cn/js/jsref_indexOf.asp

定义和用法

indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。

语法

stringObject.indexOf(searchvalue,fromindex)
参数 描述
searchvalue 必需。规定需检索的字符串值。
fromindex 可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的首字符开始检索。

说明

该方法将从头到尾地检索字符串 stringObject,看它是否含有子串 searchvalue。开始检索的位置在字符串的 fromindex 处或字符串的开头(没有指定 fromindex 时)。如果找到一个 searchvalue,则返回 searchvalue 的第一次出现的位置。stringObject 中的字符位置是从 0 开始的。

提示和注释

注释:indexOf() 方法对大小写敏感!

注释:如果要检索的字符串值没有出现,则该方法返回 -1。

实例

在本例中,我们将在 "Hello world!" 字符串内进行不同的检索:

<script type="text/javascript"> var str="Hello world!" document.write(str.indexOf("Hello") + "<br />") document.write(str.indexOf("World") + "<br />") document.write(str.indexOf("world")) </script>

以上代码的输出:

0 -1 6
ajax.ts:80 POST http://localhost:8000/api/upload 500 (Internal Server Error) ajaxUpload @ ajax.ts:80 doUpload @ upload-content.vue:191 await in doUpload upload @ upload-content.vue:130 await in upload uploadFiles @ upload-content.vue:87 handleChange @ upload-content.vue:202 callWithErrorHandling @ runtime-core.esm-bundler.js:199 callWithAsyncErrorHandling @ runtime-core.esm-bundler.js:206 invoker @ runtime-dom.esm-bundler.js:730 use-handlers.ts:30 UploadAjaxError: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Error</title> </head> <body> <pre>MulterError: Unexpected field<br> &nbsp; &nbsp;at wrappedFileFilter (E:\lucky备份\study_Express\node_modules\multer\index.js:40:19)<br> &nbsp; &nbsp;at Multipart.<anonymous> (E:\lucky备份\study_Express\node_modules\multer\lib\make-middleware.js:132:7)<br> &nbsp; &nbsp;at Multipart.emit (node:events:524:28)<br> &nbsp; &nbsp;at HeaderParser.cb (E:\lucky备份\study_Express\node_modules\busboy\lib\types\multipart.js:358:14)<br> &nbsp; &nbsp;at HeaderParser.push (E:\lucky备份\study_Express\node_modules\busboy\lib\types\multipart.js:162:20)<br> &nbsp; &nbsp;at SBMH.ssCb [as _cb] (E:\lucky备份\study_Express\node_modules\busboy\lib\types\multipart.js:394:37)<br> &nbsp; &nbsp;at feed (E:\lucky备份\study_Express\node_modules\streamsearch\lib\sbmh.js:248:10)<br> &nbsp; &nbsp;at SBMH.push (E:\lucky备份\study_Express\node_modules\streamsearch\lib\sbmh.js:104:16)<br> &nbsp; &nbsp;at Multipart._write (E:\lucky备份\study_Express\node_modules\busboy\lib\types\multipart.js:567:19)<br> &nbsp; &nbsp;at writeOrBuffer (node:internal/streams/writable:572:12)</pre> </body> </html> at getError (ajax.ts:22:10) at XMLHttpRequest.<anonymous> (ajax.ts:62:29)
最新发布
11-18
<table align="center" border="0" cellpadding="0" cellspacing="0" class="tableForm" style="table-layout: fixed;"> <colgroup> <col width="80" /> <col /><!--hide4phone.start--> <col width="80" /> <col width="380" /><!--hide4phone.end--> </colgroup> <tbody> <tr> <td style="text-align: right;">&nbsp;<span style="color: rgb(255, 0, 0);">*</span>Subject:</td> <td dbf.type="required" id="dbf.subject">&nbsp;</td> <!--show4phone.start></tr><tr><show4phone.end--> <td style="text-align: right;">&nbsp;Status:</td> <td><span id="mapping.dbf.procXSource">&nbsp;</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Responsor: <span id="mapping.dbf.responsorSource">&nbsp;</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Participants: <span id="mapping.dbf.participantsSource">&nbsp;</span></td> </tr> </tbody> </table> <div>&nbsp;</div> <div style="text-align: center;"> <h1><img src="../common/logo.png" /> [Form Name]</h1> </div> <div>[Design form here, based on the template below, or customized by yourself after the template removed]</div> <table align="center" border="0" cellpadding="0" cellspacing="0" class="tableListBorder" style="table-layout: fixed;"> <colgroup> <col width="130" /> <col /><!--hide4phone.start--> <col width="130" /> <col width="330" /><!--hide4phone.end--> </colgroup> <tbody> <tr> <td colspan="4" colspan4phone="2" dbf.source="" dbf.type="" style="background-color: lightyellow;">&nbsp;<strong>[Brief Information]</strong></td> </tr> <tr> <td class="fieldLabel" style="text-align: center; width: 147px;"><span style="color: red;">*</span>&nbsp;username</td> <td id="username" style="width: 210px;">&nbsp;</td> <!--show4phone.start--> </tr> <tr><!--show4phone.end--> <td class="fieldLabel" style="text-align: center; width: 63px;"><span style="color: red;">*</span>&nbsp;id</td> <td id="ID" style="width: 254px;">&nbsp;</td> </tr> <tr> <td class="fieldLabel" style="text-align: center;">项目名称</td> <td id="项目名称" style="width: 210px;">&nbsp;</td> <td class="fieldLabel" style="text-align: center;">装置名称</td> <td id="装置名称" style="width: 254px;">&nbsp;</td> </tr> <tr> <td class="fieldLabel" style="text-align: center;">Customer Name</td> <td id="CustomerName" style="width: 210px;">&nbsp;</td> <td class="fieldLabel" style="text-align: center;">E-NO/序列号</td> <td id="ENO号" style="width: 254px;">&nbsp;</td> </tr> <tr> <td class="fieldLabel" style="text-align: center;">产品描述</td> <td id="产品描述" style="width: 210px;">&nbsp;</td> <td class="fieldLabel" style="text-align: center;">Remark</td> <td id="Remark" style="width: 254px;">&nbsp;</td> </tr> <tr> <td class="fieldLabel" style="text-align: center;">Subject</td> <td id="subjectid" style="width: 210px;">&nbsp;</td> <td class="fieldLabel" dbf.source="" dbf.type="" id="" style="text-align: center;">&nbsp;</td> <td dbf.source="" dbf.type="" id="" style="width: 254px;">&nbsp;</td> </tr> <tr> <td colspan="4" colspan4phone="2" dbf.source="" dbf.type="" style="background-color: lightyellow;"><strong>&nbsp;</strong><strong>[Detailed Information]</strong></td> </tr> </tbody> </table> <div style="text-align: center; margin: 20px 0;">&nbsp; &nbsp; &nbsp; &nbsp; <input id="idslist" name="idslist" type="hidden" /> &nbsp;<input id="sql内容" name="sql内容" type="hidden" /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <strong> <input id="check" name="check" onclick="clickData()" type="button" value="check记录" /> </strong> <strong> <input id="check2" name="check2" onclick="clickData2()" type="button" value="下载结果" /> </strong></div> <!-- ==================== 移动端表格占位(暂不使用)==================== --><!-- ==================== 查询结果表格容器 ==================== --> <div id="resultTableContainer" style="margin-top: 20px; padding: 0 10px; min-height: 20px;"><!-- 动态表格将插入到这里 --></div> <div class="slide4phone2" id="reptable" style="display:none;"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="tableListBorder2" style="width: 1300px;"> </table> </div> <!-- ==================== 核心脚本:查询与渲染 ==================== --><script language="javascript"> function clickData() { if (window.__isQuerying) return; window.__isQuerying = true; try { var enonumber = $("ENO号")?.value ? $("ENO号").value().trim() : ""; if (!enonumber) { alert("请输入搜索内容"); return; } console.log("【原始输入】", enonumber); function escapeSql(str) { return String(str || '').replace(/'/g, "''"); } // ✅ 正确构建模糊匹配模式 const searchPattern = '%' + escapeSql(enonumber) + '%'; // ✅ 清洗字段中的各种隐藏字符 const cleanedField = ` REPLACE( REPLACE( REPLACE( REPLACE( ISNULL([ENO序列号], ''), CHAR(10), ''), CHAR(13), ''), CHAR(9), ''), ' ', '') `; var sql = ` SELECT TOP 100 Subject, Status, 申请人, 申请日期, 产品类别, 其他, type, 内勤, 系统, customer, ProjectName, DeviceName, 新产品, [ENO序列号], 目标价, 数量, 产地, 含税报价, HandlerRemark, Remark, 描述 FROM X_BPM_DWH_819_InquiryLines WHERE ${cleanedField} LIKE '${searchPattern}' ORDER BY 申请日期 DESC `; console.log("【执行SQL】", sql); var rawResult = service("common.js", "getDbsRecords", sql, "array"); let arr = parseServiceResult(rawResult); renderTable(arr); } catch (e) { console.error("查询失败", e); alert("错误:" + (e.message || e)); } finally { window.__isQuerying = false; } } /** * 安全解析 service 返回的结果 * 支持:合法JSON / 非法JSON / JS数组字面量 / 字符串化数组 / null等 */ function parseServiceResult(rawResult) { console.log("【原始返回类型】", typeof rawResult); console.log("【原始内容】", rawResult); // 情况1:已经是数组 if (Array.isArray(rawResult)) { console.log("✅ 已识别为原生数组"); return rawResult; } // 情况2:null/undefined/false if (rawResult == null || rawResult === 'null' || rawResult === 'undefined') { console.warn("⚠️ 返回为空值"); return []; } // 转为字符串处理 let str = String(rawResult).trim(); if (!str) { console.warn("⚠️ 返回空字符串"); return []; } // 情况3:可能是HTML错误页(常见于服务异常) if (str.startsWith('<') || str.includes('<html') || str.toLowerCase().includes('error') || str.includes('Exception')) { console.error("🔴 返回了HTML错误页!", str.substring(0, 200)); throw new Error('服务端错误,请检查SQL语法或联系管理员'); } /** * 数据清洗函数:修复各种非法字符 */ function clean(str) { return str .replace(/\\\\/g, '\\') // 修复多个反斜杠 .replace(/"/g, '\\"') // 先转义双引号 .replace(/'/g, '"') // 单引号 → 双引号 .replace(/\\"/g, '"') // 还原正常引号 .replace(/\\n/g, '\\n') // 显式换行 .replace(/\\r/g, '\\r') .replace(/\\t/g, '\\t') .replace(/\n/g, '\\n') .replace(/\r/g, '\\r') .replace(/\t/g, '\\t') .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, '') // 移除控制字符 .replace(/^"(\[.*\])"$/, '$1') // 去掉 "[...]" 外层引号 .replace(/^"(\{.*\})"$/, '$1') .replace(/,\s*}/g, '}') // 去除对象尾部逗号 .replace(/,\s*]/g, ']'); // 去除数组尾部逗号 } // 尝试多种解析方式 const parsers = [ // 方式1:直接JSON.parse () => JSON.parse(str), // 方式2:清洗后再解析 () => JSON.parse(clean(str)), // 方式3:作为JS表达式执行(仅限可信环境) () => new Function(`return (${str});`)(), // 方式4:进一步清理后尝试 () => JSON.parse(clean(str).replace(/""/g, '"').replace(/"\s+:/g, '":').replace(/:\s+"/g, ':"')) ]; for (let i = 0; i < parsers.length; i++) { try { const result = parsers[i](); if (Array.isArray(result)) { console.log(`✅ 第 ${i+1} 种方式解析成功`); return result; } // 兼容 { data: [...] } 结构 if (result && Array.isArray(result.data)) return result.data; if (result && Array.isArray(result.rows)) return result.rows; } catch (e) { console.warn(`📌 方式 ${i+1} 解析失败`, e.message); } } // 情况5:手动解析简单二维数组字符串 [[...],[...]] if (/^\[\s*$$[^$$]*$\s*(,\s*$$[^$$]*$)*\s*\]$/.test(str)) { try { console.log("🔍 检测到疑似二维数组字符串,尝试手动解析"); const rows = str.match(/$[^$$]*$/g) || []; return rows.map(row => { return row.replace(/^\[/, '').replace(/\]$/, '') .split(',') .map(field => field.trim().replace(/^"(.*)"$/, '$1').replace(/^'(.*)'$/, '$1')); }).filter(r => r.length > 0); } catch (e) { console.error("手动解析失败", e); } } // 所有方式都失败 console.error("🔴 所有解析方式均失败", { raw: rawResult, cleaned: clean(str) }); throw new Error('返回数据格式异常,无法解析。请检查SQL是否正确或联系开发人员。'); } /** * 渲染查询结果为表格 */ function renderTable(arr) { var container = document.getElementById("resultTableContainer"); if (!container) return; // 清空容器 container.innerHTML = ''; if (!arr || arr.length === 0) { container.innerHTML = ` <p style="text-align:center;color:#999;font-style:italic;padding:20px;"> 📭 未找到匹配的数据。 </p> `; return; } // 创建表格 var table = document.createElement('table'); table.className = 'tableListBorder'; table.style.width = '100%'; table.style.tableLayout = 'fixed'; table.setAttribute('border', '1'); table.setAttribute('cellpadding', '6'); table.setAttribute('cellspacing', '0'); table.style.fontFamily = 'Arial, sans-serif'; table.style.fontSize = '13px'; // 表头 var thead = document.createElement('thead'); var headerRow = document.createElement('tr'); var headers = [ "Subject", "Status", "申请人", "申请日期", "产品类别", "其他", "类型", "内勤", "系统", "客户", "项目名称", "装置名称", "新产品", "E-NO/序列号", "目标价", "数量", "产地", "含税报价", "处理备注", "备注", "描述" ]; headers.forEach(function(text) { var th = document.createElement('th'); th.style.backgroundColor = '#f5f5f5'; th.style.textAlign = 'center'; th.style.padding = '10px'; th.style.whiteSpace = 'nowrap'; th.style.fontWeight = 'bold'; th.textContent = text; headerRow.appendChild(th); }); thead.appendChild(headerRow); table.appendChild(thead); // 表体 var tbody = document.createElement('tbody'); arr.forEach(function(row, index) { if (!row || !Array.isArray(row) && typeof row !== 'object') { console.warn(`第 ${index} 行数据异常`, row); return; } var tr = document.createElement('tr'); Object.values(row).forEach(function(cell) { var td = document.createElement('td'); td.style.padding = '8px'; td.style.borderTop = '1px solid #eee'; td.style.wordBreak = 'break-word'; td.style.maxWidth = '200px'; td.textContent = cell == null ? '' : String(cell).trim(); tr.appendChild(td); }); tbody.appendChild(tr); }); table.appendChild(tbody); container.appendChild(table); console.log(`✅ 成功渲染 ${arr.length} 行数据`); } </script> <div id="resultTableContainer" style="margin-top: 20px; overflow-x: auto;">&nbsp;</div> 完整修复以上 [ENO序列号] 匹配问题 数值不能完全匹配
10-22
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值