gpt4 book ai didi

javascript - 获取所有 4 个字母的单词正则表达式

转载 作者:行者123 更新时间:2023-11-30 08:31:52 25 4
gpt4 key购买 nike

为了让所有 4 个字母的单词都由 any 分隔,我编写了以下代码:

function select() {
var html = document.getElementById('p').innerHTML;
var fourLettered = html.match(/[^a-zA-Z|^$][a-zA-Z]{4}[^a-zA-Z|^$]/g) || [];
document.getElementById('other').innerHTML = fourLettered.join('<br>');
}
p {
background-color: #eee;
}

.red {
color: red;
}
<p id="p" contenteditable="true">This is <i>a</i> <span class="red">paragraph</span> <b>with</b> lots of markup and-lots-of letters;with?four char</p>
<p id="other"></p>
<button onclick="select()">SELECT</button>

但是,在这种情况下,我无法获得 p 标记开头或结尾的 4 个字母单词,即 Thischar

标记/span> 也被选中。如何解决这个问题?

最佳答案

试试这个:

function select() {
var html = document.getElementById('p').textContent;
var fourLettered = html.match(/\b[a-zA-Z]{4}\b/g) || [];
document.getElementById('other').innerHTML = fourLettered.join('<br>');
}
p {
background-color: #eee;
}

.red {
color: red;
}
<p id="p" contenteditable="true">This is <i>a</i> <span class="red">paragraph</span> <b>with</b> lots of markup and-lots-of letters;with?four char</p>
<p id="other"></p>
<button onclick="select()">SELECT</button>

关于javascript - 获取所有 4 个字母的单词正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36674424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com