gpt4 book ai didi

javascript - 将特殊标签应用于所有选定文本中的文本区域,即使有换行符捕获光标位置中的所有内容

转载 作者:行者123 更新时间:2023-11-28 08:52:32 24 4
gpt4 key购买 nike

下面的示例将标记 [code] 和 [/code] 写入文本区域中的选定文本,但仅应用于字符串的开头和结尾...我想要 [code] 和 [/code]应用于字符串的每个部分,将换行符视为新字符串...

发布的示例执行:

[code]test
test
test[/code]

我想申请:

blablabla...
[code]test[/code]
[code]miao miao[/code]
[code]this is teh 3rd string[/code]
etcetera, some extra string

正如你所看到的,我想仅应用代码选定的字符串,考虑到带有换行符的新字符串......这可以在纯javascript中吗?没有 jquery 或 mootools,请仅使用独立脚本...

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>[javascript code]</title>
<script language="JavaScript" type="text/javascript">
var myValueBefore = "[code]";
var myValueAfter = "[/code]";
function applyCode(myField, myValueBefore, myValueAfter) {
if (document.selection) {
myField.focus();
document.selection.createRange().text = myValueBefore + document.selection.createRange().text + myValueAfter;
} else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)+ myValueBefore+ myField.value.substring(startPos, endPos)+ myValueAfter+ myField.value.substring(endPos, myField.value.length);
}
}
</script>
</head>

<body>

<br><br><br>
<table align="center" border="0" cellpadding="15" cellspacing="0" width="70%">
<tr>
<td>
<form action="#" method="post">
<input type="button" value="Apply Code" onclick="javascript:applyCode(test, myValueBefore, myValueAfter);"><br>
<textarea rows="5" cols="130" name="test"></textarea>
</form>
</td>
</tr>
</table>

</body>

</html>

最佳答案

您可以进一步开发此代码片段:

var myValueBefore = '[code]',
myValueAfter = '[/code]';
function applyCode(myField, myValueBefore, myValueAfter) {
var newLine = new RegExp('\n|\r\n', 'g'), range, selectedText, beforeSelectedText, afterSelectedText;
if (document.selection) {
range = document.selection.createRange();
range.text = myValueBefore + range.text.replace(newLine, myValueAfter + '\n' + myValueBefore) + myValueAfter;
return;
} else {
beforeSelectedText = myField.value.substring(0, myField.selectionStart);
afterSelectedText = myField.value.substr(myField.selectionEnd);
selectedText = myField.value.substring(myField.selectionStart, myField.selectionEnd);
myField.value = beforeSelectedText + myValueBefore + selectedText.replace(newLine, myValueAfter + '\n' + myValueBefore) + myValueAfter + afterSelectedText;
}
return;
}

A live demo at jsFddle .

关于javascript - 将特殊标签应用于所有选定文本中的文本区域,即使有换行符捕获光标位置中的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18977932/

24 4 0