首页 > 解决方案 > 根据 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>

标签: javascriptpythonhtmlindexing

解决方案


使用 lastIndexOf()

let c = s.substring(0, s.lastIndexOf('?'));

文档:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf


推荐阅读