How can I change * to italic javascript?

I'm trying to change the (display) style *to italicuser input textarea when the button is pressed. But nothing works without errors, I think my logic is a little wrong, but can no longer figure !!!

var italic = 0;
$("#btn").click(function(){
        var val = $("#usr").val();
        val.split("").forEach(function(v,i){
            var sts = /\*/g.test(v);
            if(sts){
                if(italic == 1){
                val.substr(0, i) + '</i>' + val.substr(i + 1);
                italic = 0;
                }
                else{
                val.substr(0, i) + '<i>' + val.substr(i + 1);
                italic++;
                }
            }
        });    
        $("#display").html(val);
});
#display {
    background: #aaa;
    width: 30%;
    height: auto;
    border: 1px solid #ded;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<textarea id="usr"></textarea>
<button id="btn">Insert</button>
<div id="display"></div>
Run code
+4
source share
3 answers

Use simple \*(.*?)\*to output output to a tag <i>:

$(document).ready(function() {
  $('textarea').keyup(function() {
    $('#output').html($(this).val().replace(/\*(.*?)\*/g, '<i>$1</i>'));
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>
<div id="output"></div>
Run code

RegEx explained:

\* - literal * (* RegEx )
.*? -
() - , $1, $2... ((.*?) - )
/ - RegEx (

\*(.*?)\* - *, , *

+6

val.split(""), .each , RegExp , v == "*"

italic italicTagOpened italicTagOpened = !italicTagOpened;

, , output

var italicTagOpened = false;
$("#btn").click(function(){
  var val = $("#usr").val(),
      output = "";

  val.split("").forEach(function(v,i) {
    //var sts = /\*/g.test(v);
    if(v == "*"){
      if(italicTagOpened) output += "</i>";
      else output += "<i>";

      italicTagOpened = !italicTagOpened;
    } else output += v;
  });    
  $("#display").html(output);
});

https://jsfiddle.net/uyjqerg4/1/

+1

var italic = 0;
$("#btn").click(function(){
        var val = $("#usr").val();
        val = val.replace(/\*/g, '<i>*</i>');
        $("#display").html(val);
});
#display {
    background: #aaa;
    width: 30%;
    height: auto;
    border: 1px solid #ded;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<textarea id="usr"></textarea>
<button id="btn">Insert</button>
<div id="display"></div>
Run code

You can simply use the javascript replacement function, the first argument can take a regular expression. The backslash (\) is intended to escape (since * in the regular expression has a different meaning than just *), and g means "global".

-1
source

Source: https://habr.com/ru/post/1652956/


All Articles