18910140161

替换HTML页面上所有出现的子字符串,而不使用replaceAll,并将大小写保持为原始

顺晟科技

2021-08-15 10:52:06

57

我正在尝试替换输入给出的子字符串的所有匹配项,而不使用replaceAll,并将大小写保持为原始匹配项。这就是我现在拥有的:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <input class="searchInput" type="text">
    <p id="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illum adipisci a quia quas reiciendis. Consectetur excepturi iusto, corporis sapiente cupiditate quae sequi nobis voluptatibus ullam cum suscipit quibusdam quo maiores.</p>
    <script type="text/javascript">
        var searchInput = document.querySelector('.searchInput')
        var text = document.querySelector('#text')
        function displayMatches(e) {
            var regex = new RegExp(e.target.value, 'ig')
            var response = text.innerText.replace(regex, function(match) {
                return text.innerText.split(regex).join("<span style='background-color: yellow;'>" + match + "</span>")
            })
            text.innerHTML = response
        }
        searchInput.addEventListener('change', displayMatches)
        searchInput.addEventListener('keyup', displayMatches)
    </script>
</body>
</html>

但它并不像预期的那样工作。我使用replaceAll实现了我想要的,如下所示:

var searchInput = document.querySelector('.searchInput')
var text = document.querySelector('#text')
function displayMatches(e) {
    var regex = new RegExp(e.target.value, 'ig')
    var response = text.innerText.replaceAll(regex, function(match) {
        return "<span style='background-color: yellow;'>" + match + "</span>"
    })
    text.innerHTML = response
}
searchInput.addEventListener('change', displayMatches)
searchInput.addEventListener('keyup', displayMatches)

但是我想知道是否可以不使用replaceAll(由于跨浏览器的原因)使用split 'n join或其他方法来实现。


顺晟科技:

  • TAG:
相关文章
随机推荐
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航