Reputation: 2538
I'm building an app that has a textarea that needs formatting. I don't want to use a contenteditable
div, so I think the next best solution is to use a normal textarea and replace characters with a tag afterwards.
The formatting is similar to Reddit or 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>
So from this example, when Submit
is pressed I would need:
* becomes <b></b>
_ becomes <i></i>
#c# becomes <span class="myClass"> </span>
How could I do this? Thank you
Upvotes: 0
Views: 371
Reputation: 2531
This does more:
var tags = {
"*": ["<b>", "</b>"],
"_": ["<span class='myClass'>", "</span>"]
}
var el = document.getElementById("editor"),
val = htmlize(el.value),
display = document.getElementById("display");
display.innerHTML = val;
el.addEventListener("change", function(){
val = htmlize(el.value);
display.innerHTML = val;
});
function htmlize(content){
for(var i in tags){
var reg = "\\"+i+"\\s?(\\w+)";
reg = new RegExp(reg, "g");
content = content.replace(reg, function(match, w){
return tags[i][0]+w+tags[i][1];
});
}
return content;
}
<textarea id="editor">
I'm so great * awesome dude and _ fantastic person. You * Should know this
</textarea>
<p id="display"></p>
Upvotes: 1
Reputation: 620
You can easily replace even / odd occurrences of a string in a string with regular expressions. For example:
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);
Upvotes: 1