How to apply a style to a certain area in a textarea in HTML, CSS, JS
Hello I would like to take the string I get from a textarea, then look for certain words in that string, then apply a style to them. How would I do that?
it's not possible in a textarea but I think this works
<p contenteditable="true">ooga booga <span style="color:red;">ooga</span> booga ooga booga </p>
oh yeah btw
if you are thinking of making a code editor... don't do this
it'll cause more pain than anything, considering you could use something that replit uses, in half the time
unless ur making a Microsoft word, you should probably reconsider
If I understand you correctly, I think I have an answer,
First, you'd have to get the string from the text area, so you would select the text area,
Then you'd have to select the text inside,
That should give you a string with whatever is inside of the text area, you could save the string to a variable if you want, whatever you want to do you can. Next, there's a special function for finding certain words or phrases in strings: the .indexOf() function,
var myString = 'Hello World'
The output of this would be 0, this is because the indexOf() function gives you the index number of the first letter of the word/phrase and a -1 if that phrase isn't there. Unfortunately, this only works for the first appearance of the word/phrase so if the word/phrase appears more than once I don't know how to help with the finding certain words part. Applying styles to them is simple, but I honestly only found these links today when I had the same issue.
Not quite sure how to do the latter (apply a style), but here's the start:
For this, you can use DOM. First, you can get the value of the textarea with
var str document.getElementById("#id of your textarea").value
Then, you can use
.search() to find some words:
var after = str.search("W3Schools")
And to apply style, you can also use DOM. For example, you can get an element and color it red:
document.getElementById("thing").style.color = "red"
Good luck! :D