gpt4 book ai didi

javascript - 用 html 标签替换文本区域中的字符

转载 作者:行者123 更新时间:2023-12-01 01:28:20 25 4
gpt4 key购买 nike

我正在构建一个具有需要格式化的文本区域的应用程序。我不想使用 contenteditable div,所以我认为下一个最佳解决方案是使用普通的文本区域,然后用标签替换字符。

格式类似于 Reddit 或 Slack..

$( '.actionBtn' ).on('click', function(){
var cursorPos = $('#text').prop('selectionStart');
var cursorPosEnd = $('#text').prop('selectionEnd');
var v = $('#text').val();
var textBefore = v.substring(0, cursorPos );
var textSelected = v.substring( cursorPos, cursorPosEnd );
if(textSelected == "") {
textSelected = "text here"
}
var textAfter = v.substring( cursorPosEnd, v.length );
$('#text').val( textBefore + $(this).val() + textSelected + $(this).val() + textAfter );
});

$( '#submitBtn' ).on('click', function(){
//TODO: switch to tags
// * becomes <b></b>
// _ becomes <i></i>
// #c# becomes <span class="myClass"> </span>
$('#result').html($('#text').val())
});
.myClass {
color: #FF0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div>
<textarea id="text" cols="40" rows="3"></textarea>
</div>
<div>
<input class="actionBtn" type="button" value="*" />
<input class="actionBtn" type="button" value="_" />
<input class="actionBtn" type="button" value="#c#" />
</div>
<div>
<input id="submitBtn" type="button" value="Submit" />
</div>
<p id="result">

</p>
</form>

因此,从这个示例中,当按下Submit时,我需要:

* becomes <b></b>
_ becomes <i></i>
#c# becomes <span class="myClass"> </span>

我怎样才能做到这一点?谢谢

最佳答案

您可以使用正则表达式轻松替换字符串中偶数/奇数出现的字符串。例如:

const regex = /\_(.*?)\_/gm;
const str = `Lorem _ipsum_ dolor sit amet, _consectetur adipiscing_ elit, sed
do _eiusmod_ tempor `;
const subst = `<em>$1</em>`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);

Check it online

关于javascript - 用 html 标签替换文本区域中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53545990/

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