[英]How to find '>' and wrap into a <span> tag without nesting?
I am trying to find >
sign in editable div
with REGEX
, replace it wrapping in span.我正在尝试使用
REGEX
查找>
登录可编辑的div
,将其替换为跨度换行。 The script( REGEX
) works, but it has a few bugs.脚本(
REGEX
)有效,但有一些错误。
If I type >
sign 2 times dividing them by space like > >
, it creates the following.如果我输入
>
符号 2 次将它们除以空格,例如> >
,它会创建以下内容。
<span>
<span>></span>
>
</span>
Instead I need this without nesting:相反,我不需要嵌套:
<span>></span>
<span>></span>
Also If I type >
2 times without space like >>
, REGEX
should take each >
sign and wrap it into a separate span
, like this:此外,如果我键入
>
2 次没有空格,例如>>
,则REGEX
应将每个>
符号包装成一个单独的span
,如下所示:
<span>></span>
<span>></span>
Here is my code:这是我的代码:
<div class="editable" contenteditable="true"></div>
.editable{
height: 20px;
border: 1px solid grey;
cursor: text;
white-space: pre-wrap;
}
span{
white-space: pre-wrap;
}
var createRange = function (node, chars, range) {
if (!range) {
range = document.createRange()
range.selectNode(node);
range.setStart(node, 0);
}
if (chars.count === 0) {
range.setEnd(node, chars.count);
} else if (node && chars.count >0) {
if (node.nodeType === Node.TEXT_NODE) {
if (node.textContent.length < chars.count) {
chars.count -= node.textContent.length;
} else {
range.setEnd(node, chars.count);
chars.count = 0;
}
} else {
for (var lp = 0; lp < node.childNodes.length; lp++) {
range = createRange(node.childNodes[lp], chars, range);
if (chars.count === 0) {
break;
}
}
}
}
return range;
};
var setCurrentCursorPosition = function (chars) {
if (chars >= 0) {
var selection = window.getSelection();
range = createRange(document.querySelector('.editable'), { count: chars });
if (range) {
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
}
}
};
$('.editable').on('keydown', function() {
if( new RegExp(/(?!<span>)>(?!<\/span)/, 'g').test($(this).html()) ) {
$(this).html(
$(this).html().replace(/(?!<span>)>(?!<\/span)/g, '<span>></span>')
);
setCurrentCursorPosition( $(this).text().length );
}
});
You can ignore createRange
, setCurrentCursorPosition
functions.您可以忽略
createRange
、 setCurrentCursorPosition
函数。 They just move the cursor when typing >
into the div
.他们只是在将
>
输入div
时移动光标。
Use html entities使用 html 实体
<span>></span>
Documentation: https://www.w3schools.com/html/html_entities.asp
文档: https : //www.w3schools.com/html/html_entities.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.