javascript - 根据 JavaScript 中的索引选择字符串
问题描述
如何让 p 标记仅显示指定索引范围内的文本(这里是特殊字符('?')。)...如果有相反的方法(在我可能的情况下)连接了多个相似的特殊字符(例如:Hello ...),我想选择最后一个),例如 python“rindex”方法,我也想知道这一点。
**JavaScript**
function check(){
var s = document.getElementById("text").innerHTML;
var c;
c = s.substring(0, s.indexOf('?'));
}
**HTML**
<button id="check" type="submit" onclick="check()">Check</button>
<p id="text"> Hello, what's up with you? Haven't seen you in ages!</p>
解决方案
使用 lastIndexOf()
let c = s.substring(0, s.lastIndexOf('?'));
文档:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf
推荐阅读
- botframework - 选择提示不会在 MS Bot 框架中呈现按钮
- java - 未使用 Webflux 生成 CSRF 令牌
- python - 如何获取 1 列值并将其中一些值放入基于布尔标志列的新列中?
- c - C-如何使变量成为大端。默认?
- angular - 自定义错误处理程序中的 RxJS 传递函数
- c++ - 我的神经网络不起作用 [XOR 问题]
- ios - Swift 3:您可以将代码存储在变量中然后在 tableview 加载时运行它吗?
- curl - Azuracast - 带有 API 密钥的 Swagger API PHP Curl POST
- reactjs - 使用 React Native 和 Expo 创建 OSM 地图应用
- mongodb - MongoDB 在 bulkWrite() 上更改流