How to highlight a part of text in textarea
without wrapping a tag around the specific words, you cannot highlight it (or as i said, at least I have no idea how to).
but if there is no problem with wrapping tags, you should use regEx.
for words starting with @ :
replace(/@([^ ]+)/g, '<span class="atsign">@$1</span>');
and for the words starting with # :
status.replace(/#([^ ]+)/g, '<span class="hashtag">#$1</span>');
check this fiddle
EDIT: you can replace
var status = 'I tweeted something #one #two @three @four';
with
var status = $('#phrase').text();
Is it any way to highlight text in <textarea>?
You can't actually highlight text in a <textarea>
. Any markup you would add to do so would simply display as plain text within the <textarea>
. But you can carefully craft some CSS and Javascript code to fake it:
Please check out this article Highlight Text Inside a Textarea for more information on how it can be crafted.
Highlight words inside of input textarea
Unfortunately you cannot change the style dynamically of a text area input.
However, a possible workaround is to display the text the user is writing below the text area. In that way the text will dynamically change as the user is writing and you can apply the specific styling for that array of words.
You could even set the text area to not display the text and in that way the user would only see its input below with the right feature.
Highlight specific words in textarea angular 8
This answer is based on the link provided by @RobinDijkhof in there comment.
We will set up the css exactly as provided
*,
*::before,
*::after {
box-sizing: border-box;
}
.container,
.backdrop,
textarea {
width: 460px;
height: 180px;
}
.highlights,
textarea {
padding: 10px;
font: 20px/28px "Open Sans", sans-serif;
letter-spacing: 1px;
}
.container {
display: block;
margin: 0 auto;
transform: translateZ(0);
-webkit-text-size-adjust: none;
}
.backdrop {
position: absolute;
z-index: 1;
border: 2px solid #685972;
background-color: #fff;
overflow: auto;
pointer-events: none;
transition: transform 1s;
}
.highlights {
white-space: pre-wrap;
word-wrap: break-word;
color: transparent;
}
textarea {
display: block;
position: absolute;
z-index: 2;
margin: 0;
border: 2px solid #74637f;
border-radius: 0;
color: #444;
background-color: transparent;
overflow: auto;
resize: none;
transition: transform 1s;
}
mark {
border-radius: 3px;
color: transparent;
background-color: #b1d5e5;
}
.perspective textarea {
transform: perspective(1500px) translateX(155px) rotateY(45deg) scale(1.1);
}
textarea:focus,
button:focus {
outline: none;
box-shadow: 0 0 0 2px #c6aada;
}
Now to the task will be to convert the JQuery code to Angular. We will build a component that can be used like
<app-textarea-highlight [(ngModel)]='txt'
[highlightTexts]='highlightTexts'
></app-textarea-highlight>
Where the values are
highlightTexts = ["text", "demo", "div"];
txt = "This demo shows how to highlight bits of text within a textarea. Alright, that's a lie. You can't actually render markup inside a textarea. However, you can fake it by carefully positioning a div behind the textarea and adding your highlight markup there.
}
To enable using property binding we will implement ControlValueAccessor
Below is the code
@Component({
selector: "app-textarea-highlight",
templateUrl: "./textarea-highlight.component.html",
styleUrls: ["./textarea-highlight.component.css"],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => TextareaHighlightComponent),
multi: true
}
]
})
export class TextareaHighlightComponent
implements ControlValueAccessor {
constructor() {}
@Input() highlightTexts: string[] = [];
@ViewChild("backdrop") $backdrop: ElementRef<HTMLDivElement>;
@ViewChild("textarea") $textarea: ElementRef<HTMLTextAreaElement>;
textValue: string = "";
get highlightedText () {
return this.applyHighlights(this.textValue)
}
applyHighlights(text) {
text = text ? text
.replace(/\n$/g, "\n\n") : '';
this.highlightTexts.forEach(x => {
text = text
.replace(new RegExp(x, 'g'), "<mark>$&</mark>");
})
return text;
}
handleScroll() {
var scrollTop = this.$textarea.nativeElement.scrollTop;
this.$backdrop.nativeElement.scrollTop = scrollTop;
var scrollLeft = this.$textarea.nativeElement.scrollLeft;
this.$backdrop.nativeElement.scrollLeft = scrollLeft;
}
onChanges: ($value: any) => void;
onTouched: () => void;
writeValue(value: any): void {
if (value !== undefined) {
this.textValue = value;
}
}
registerOnChange(fn: any): void {
this.onChanges = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
}
The final step is to set the html
<div class="container">
<div #backdrop class="backdrop">
<div class="highlights" [innerHTML]="highlightedText"></div>
</div>
<textarea
[(ngModel)]="textValue"
(scroll)="handleScroll()"
#textarea
></textarea>
</div>
See Working Demo Here
how to highlight part of textarea html code
There is a pre
element over the textarea. So when you type anything it is copying the input on the pre
element, applying some filters.
For example:
<pre id="view"></pre>
<textarea id="code"></textarea>
When you type on #code
it is copying the value, applying filters and adding the HTML to the #view
.
var code = document.getElementById("code");
var pre = document.getElementById("pre");
(code).onkeyup = function (){
val = this.value;
val = YourRegex(val);
(pre).innerHTML = val;
};
YourRegex
would be a method to match the regex
and return some parsed content to the pre
, allowing you to customize the appearance of the textarea
(that is actually an element over it).
function YourRegex(val)
{
// This function add colors, bold, whatever you want.
if (/bbcc/i.test("bbcc"))
return "<b>" + val + "</b>";
}
JQuery/JavaScript - highlight a part of text from input or textarea
You have to place a div
behind your textarea
and then style it according to it's text.
Notes:
- Set your
textarea
background-color
to transparent to see yourhighlighter
color. - Your
highlighter
have to be the same style and text content of yourtextarea
to put thespan
on the right place. - Set your
highlighter
text to the same color of it's background or you'll see a<b>
effect, the same for thespan
.
html:
<div class="highlighter">some text <span>highlighted</span> some text</div>
<textarea>some text highlighted some text</textarea>
css:
.highlighter, textarea {
width: 400px;
height: 300px;
font-size: 10pt;
font-family: 'verdana';
}
.highlighter {
position: absolute;
padding: 1px;
margin-left: 1px;
color: white;
}
.highlighter span {
background: red;
color: red;
}
textarea {
position: relative;
background-color: transparent;
}
demo
How to change the highlight color of selected text in a textarea, using selection range?
I don't understand exactly what you want.
Did you want an answer like the code below?
https://codepen.io/jyh7a/pen/xxpLMZZ
HTML
<input type="text" id="text-box" size="20" value="Mozilla">
<button onclick="selectText()">Select text</button>
<hr/>
<textarea rows="6" cols="40">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Porro maxime excepturi autem nostrum minus quae magni, esse optio ab, dolor ut iste earum sapiente molestiae nihil totam rem ipsam officia?</textarea>
<hr/>
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Porro maxime excepturi autem nostrum minus quae magni, esse optio ab, dolor ut iste earum sapiente molestiae nihil totam rem ipsam officia?</p>
CSS
::selection {
background-color: rgba(255,0,0,0.2);
}
JS
function selectText() {
const input = document.getElementById('text-box');
input.focus();
input.setSelectionRange(2, 5);
setTimeout(() => {
const textarea = document.querySelector('textarea');
textarea.focus();
textarea.setSelectionRange(0, 20);
}, 1000)
// // ERROR!
// // setSelectionRange function only use HTMLInputElements
// const p = document.querySelector('p');
// p.setSelectionRange(0, 20);
}
I searched for setSelectionRange
I made the above example by looking at the MDN official documentation.
(Link: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange )
Hope the above code was helpful to you.
Related Topics
Replace Unicode Matches in JavaScript
Html - Clicking a Button to Obtain Table Cell Value
Convert Hex to Binary in JavaScript
Set Focus to the Next Input Element
Vue.Js Refs Are Undefined, Even Though This.$Refs Shows Theyre There
How to Compare Two Arrays Using Lodash (The Order Matters)
How to Get Route Url Params in a Page in Nuxt2 and 3
How to Fix Problem Closing Dropdown When I Click Outside It
Can We Call the Function Written in One JavaScript in Another Js File
How to Separate an Integer into Separate Digits in an Array in JavaScript
How to Align Text Input Correctly in React Native
How to Loop Over Object Properties With Ngfor in Angular
What Do Square Brackets Around an Expression Mean, E.G. 'Var X = a + [B]'
How to Know If Browser Tab Is Already Open Using JavaScript
Regex to Match Words With Hyphens And/Or Apostrophes