我想搜索我页面上可用的所有长度为 4 的单词或文本,并将其替换为使用正则表达式的函数返回的其他文本
$("#changeRandom").click(function() {
$("body").children().each(function() {
$(this).text($(this).text().replace(/([a-zA-Z]){4}/g,"hello"));
});
});
最佳答案
这里不需要循环也不需要jQuery,用Js就可以简单的完成。但是由于您对 jQuery 的偏好从您的代码中显而易见,您可以通过 3 个简单的步骤完成这件事:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Stack Overflow is a privately held website, the flagship site of the Stack Exchange Network. Stack Overflow is a privately held website, the flagship site of the Stack Exchange Network.Stack Overflow is a privately held website, the flagship site of the Stack Exchange Network.</p>
<button onclick="replaceFunction()">Replace overflow with exchange</button>
<script>
function replaceFunction() {
var repWith ="exchange";
var content = $("body").html();
var result = content.replace(/overflow/gi, repWith);
$("body").html(result);
}
</script>
关于javascript - 从页面中查找长度为 4 的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37084579/