1

I am trying to get a textbox to change text in a div, and if square brackets are added I want a span to be added around the text to make the text green. Here is my code so far:

function greenText() {
  var textAreaText = $('#textarea').val();
  var replacedText = textAreaText.replace("[", "<span style='color:green'>").replace("]", "</span>");
  $('#preview').html(replacedText);
}

$(function() {
  greenText();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="preview" style="height: 4em; background-color:#eee; padding:10px;"></div>
<textarea id="textarea" rows="4" cols="50" onchange="greenText();" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();">
  At w3schools.com you will learn how to [make a website]. 
</textarea>

The greenText function works when the page loads, however when I am adding in brackets updating the preview div it prints the square brackets out to the page rather than the span tags. Does any one have any idea why the function isn't replacing the text?

eisbehr
  • 12,243
  • 7
  • 38
  • 63
Ginger Squirrel
  • 663
  • 7
  • 22
  • Now that it is marked as duplicate I know what the issue is, the replace was only changing the first pair of brackets that it came across, rather than all of them in the string. I thought the issue lied with calling the function multiple times, or the HTML was being stripped out somewhere. – Ginger Squirrel May 22 '18 at 11:38

1 Answers1

2

For multiple replaces inside a string you need to use RegEx:

function greenText() {
  var textAreaText = $('#textarea').val();
  var replacedText = textAreaText.replace(/\[/g, "<span style='color:green'>").replace(/\]/g, "</span>");
  $('#preview').html(replacedText);
}

$(function() {
  greenText();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="preview" style="height:400px; background-color:#eee; padding:40px;"></div>
<textarea id="textarea" rows="4" cols="50" onchange="greenText();" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();">
  At w3schools.com you will learn how to [make a website]. 
</textarea>
eisbehr
  • 12,243
  • 7
  • 38
  • 63