how to search highlight count occurences using angular pipes - javascript

I have below angular pipe code to search and highlight the text
Let's suppose pets.description has huge description text in below html file
<div class="search-input">
<label for="">Search here: </label> <input [(ngModel)]="searchText" type="search">
</div>
<div class="text-contaniner" [innerHtml]="text" >
</div>
and
export class AppComponent {
searchText='';
text=`somedummy text here`
}
style.css
.highlight {
background-color: violet;
font-weight: bold;
}
below is the actual pipe created
transform(value: any, args: any): unknown {
if(!args) return value;
const re = new RegExp("\\b("+args+"\\b)", 'igm');
value= value.replace(re, '<span class="highlighted-text">$&</span>');
return value;
}
This code searches the text and hihglights it.How do I also show the count occurrence of matches apart from highlighting the texts.

Related

How can I change all text to Americanized spelling using Javascript/jQuery?

I have two websites, one for the UK and one for the US, both of which use the same text in some places, spelled in the British way - e.g. "I specialise in optimising stuff"
Is there a Javascript/JQuery package/solution to automatically replace all the British spelling that it finds in the DOM, to American spelling? E.g. change the above to "I specialize in optimizing stuff"
So I suppose I could loop through the DOM elements and replace them, eg
$('p').each(function() {
var text = $(this).text();
text = text.replace('ise', 'ize');
$(this).text(text);
});
But this won't work in all cases, e.g. "wise" should not be changed to "wize". Are there any known regex or similar solutions to solve this?
Here is a solution that uses a translation table and some jQuery and native JavaScript to traverse the DOM and to change text, excluding tag attributes. Click on the Switch to USA Spelling button:
const translations = {
colour: 'color',
colours: 'colors',
Colour: 'Color',
Colours: 'Colors',
optimising: 'optimizing',
specialise: 'specialize'
};
const regex = new RegExp('\\b(' + Object.keys(translations).join('|') + ')\\b', 'g');
console.log('regex', regex);
$(document).ready(function() {
$('.switchSpelling button').click(function() {
$('#mainContent *').contents().each(function() {
if(this.nodeType == 3) {
this.nodeValue = this.nodeValue.replace(regex, m => {
return translations[m];
});
}
});
})
});
.switchSpelling {
float: right;
margin-right: 70px;
}
.grayBackgroundColour {
background-color: #f0f0f0;
padding: 3px 10px;
}
.yellowBackgroundColour {
background-color: #fffff0;
padding: 3px 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mainContent">
<div class="switchSpelling">
<button>Switch to USA Spelling</button>
</div>
<h1>The history of Colour</h1>
<div class="grayBackgroundColour">
<h2>Colours in Renaissance</h2>
<p>We specialise in optimising and restoring colours</p>
</div>
<div class="yellowBackgroundColour">
<h2>Colours in Cubism</h2>
<p>We specialise in optimising and restoring colours</p>
</div>
</div>

How do I change ::selected in JavaScript? [duplicate]

I'm searching online and I didn't find anything.
I'm trying to update the placeholder color of a textbox using javascript, but how can I do that?
I have a color picker and the color is changing.
If I have something like this in my CSS, how can I update it?
::placeholder {
color: red;
}
<input placeholder="placeholder" />
Is there a javascript command to edit this?
Something like
document.getElementById('text').style.placeholderColor = newColor;
Use CSS variables. You can also target only the needed element
function update() {
document.querySelector('input[type=text]').style.setProperty("--c", "blue");
}
::placeholder {
color: var(--c, red);
}
<input type="text" placeholder="I will be blue">
<input type="number" placeholder="I will remain red">
<button onclick="update()">change</button>
CSS variables are useful when it comes to modify pseudo elements that you cannot access with JS such as :before/:after/::placeholer/::selection, etc. You simply define your custom property that you can easily update on the main element and the pseudo element will inherit it.
Related : Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery
As stated in the other answers, you cannot change pseudo-element styles inline. However, you can modify the CSS rule in the <style> itself, and you don't need a browser support ing CSS variables for that. Access the stylesheet and either get the existing rule or insert your own, then play with its style declarations like you would with an element .style:
const {sheet} = Object.assign(document.head.appendChild(document.createElement("style")), {type: "text/css" });
const placeholderStyle = sheet.rules[sheet.insertRule("::placeholder {}")].style;
placeholderStyle.color = "red";
Object.assign(document.body.appendChild(document.createElement("input")), {
type: "button", value: "Color!", onclick() {
placeholderStyle.color = "#"+Math.round(Math.random()*0xFFF).toString(16).padStart("0",3);
}});
<input placeholder="placeholder" />
There is another approach, but it's somewhat hacky: use JS to append more CSS to the end of the body. Browsers will override current CSS with the newest CSS, assuming the rules are identical.
function changeColor(toColor) {
addCSS = document.createElement('style');
addCSS.innerHTML = "::placeholder { color: " + toColor + "; }";
document.body.append(addCSS);
}
::placeholder { color: green; }
<input type="text" placeholder="placeholder">
<button onclick="changeColor('red')">red</button>
<button onclick="changeColor('blue')">blue</button>
The snippet below works without needing to make any changes to any existing CSS. You would need to modify it to work with your color picker, but hopefully this will give you something to start with.
const placeholder = document.createElement("style");
placeholder.innerHTML = `::placeholder { color:red;font-weight:bold;font-size:1.25rem;} #plchld { font-size:1.25rem;text-align:center; } `;
const plchld = document.getElementById("plchld");
plchld.addEventListener("click", function () {
plchld.setAttribute("placeholder", "Now I'm Bright Red!");
document.form.appendChild(placeholder);
});
plchld.addEventListener("blur", function () {
plchld.setAttribute("placeholder", "now I'm a dreary gray again...");
document.form.removeChild(placeholder);
});
<form name="form" action="">
<input type="text" id="plchld" size="28" placeholder="I'm currently a dreary shade of gray...">
</form>
If the placeholder color semantics depends on some state, it can be set indirectly
::placeholder { color: green; }
.warn::placeholder { color: red; }
<input id="test" placeholder="hello">
<button onclick="test.classList.toggle('warn')">Warning!</button>
In many cases this doesn't require javascript at all:
::placeholder { color: green; }
.color::after { content: 'green'; }
:checked + .color + ::placeholder { color: red; }
:checked + .color::after { content: 'red'; }
<input type="checkbox" id="color01">
<label class="color" for="color01">Color: </label>
<input placeholder="hello">

How to put ₹ symbol in front of the text in a text-box, ₹ Shouldn't be editable? [duplicate]

This question already has answers here:
HTML text input field with currency symbol
(17 answers)
Closed 2 years ago.
I have a textbox that displays the amount in Rupee.
I want the ₹ symbol in front of the amount (₹250), the ₹ symbol should not be editable but the amount(text) in the text box should be editable.
<input type="text" value="₹">
How can this be implemented?
Another solution would be to use a <label> tag in front of the input:
label {
position:relative;
left:+15px;
}
input {
text-align:right;
}
<label for="abc">₹</label><input type="text" id="abc"/>
If you don't want to add any js logic, then you should add a wrapper and hardcode the currency there.
Ideally, this is a perfect scenario for using css pseudoclasses, as :before.
The idea is to add that fixed character from css:
input:before {
content: '₹';
}
Unfortunately, pseudoclasses don't work on self-closing HTML elements, like <input /> (here's a more in-depth explanation of why this happens: https://stackoverflow.com/a/27708091/491075), so you'd have to add a wrapper to your input that would eventually hold the currency symbol.
Here's a simple example of how you could do that:
.input-wrapper {
position: relative;
}
.input-wrapper:before {
content: attr(data-currency);
position: absolute;
left: 0.25em;
top: 0;
}
.input-wrapper > input {
text-indent: 1em;
}
<div class="input-wrapper" data-currency="₹">
<input type="number" />
</div>
<div class="input-wrapper" data-currency="$">
<input type="number" />
</div>
<div class="input-wrapper" data-currency="€">
<input type="number" />
</div>
If you can't or don't want to alter the DOM, then you could use javascript to listen to any change on the input and have the currency prepended to the value.
Here's a very simple example of how you could achieve this in plain js:
const currencySymbol = '$'
const input = document.getElementById('currency-input')
input.addEventListener('keyup', function(e) {
input.value = input.value[0] === currencySymbol
? input.value
: `${currencySymbol}${input.value}`
})
<input id="currency-input" value="$0" />
You can use css ::before
Give your input a class of currency
<input type="text" value="₹" class="currency">
Then add this to your css
.currency::before{
content: "₹";
.. any other properties like width, height, position, size, color etc..
}
The symbol will appear outside, in front of the input not inside the input. You can use position and padding to place it inside though.

Setting HTML Style Using Javascript String Literal - Colon Breaks String Variable

I'm trying to set the style on an HTML element before appending it to the page by passing the style tag through a variable in a JavaScript string literal.
So my code looks like this:
const STYLE = "font-weight: bold; color: crimson; background-color: red;"
const item = `<p class="text" style=${STYLE}>Some Text</p>`
const position = "beforeend";
list.insertAdjacentHTML(position, item);
When I run it though, the HTML on the page looks like this - the quotation mark on the style tag ends after the first colon. Is there any way to get the full string into the style tag?
<p class="text" style="font-weight:" bold; color: crimson; background-color: red;>Some Text</p>
const item = `<p class="text" style=${STYLE}>Some Text</p>
You should wrap ${STYLE} with ":
const item = `<p class="text" style="${STYLE}">Some Text</p>
Browsers for attributes values without " are adding them themselves and closing them before the first space in the string. That's why "font-weight:" was wrapped here:
style="font-weight:" bold; color: crimson; background-color: red;>

Replace text inside HTML leaving other HTML intact with vanilla javascript

I'm trying to write pure javascript function to replace the text "Passed" to "Completed". The HTML inside the div#prompt should remain in tact and is variable. Here is the HTML -
<div id="prompt">
Passed
Take a survey
<button type="button" data-behavior="hide.prompt"></button>
</div>
I tried replacing text but that doesn't seem to be working
var text = document.getElementById('prompt').textContent;
text.replace("Passed", "Completed");
Also tried this -
var text = document.getElementById('prompt').innerHTML;
text.replace("Passed", "Completed");
What am I doing wrong? Appreciate the help!
replace does not mutate the string, it returns a new one. Strings are immutable.
var text = document.getElementById('prompt');
text.textContent = text.textContent.replace("Passed", "Completed");
Actually your element contains a text node that you can override:
document.getElementById('prompt').childNodes[0].textContent = "Completed";
Instead of replacing text, how about toggle a class on the outer div.
With that you can also customize its HTML as well.
Stack snippet
.prompt::before {
content: 'Passed';
}
.prompt.hidden::before {
content: 'Completed';
}
.prompt.hidden button {
display: none;
}
/* demo styles */
.prompt button { padding: 5px 20px; }
hr { margin: 20px 0; }
<div class="prompt">
Take a survey
<button type="button" data-behavior="hide.prompt"></button>
</div>
<hr>
<div class="prompt hidden">
Take a survey
<button type="button" data-behavior="hide.prompt"></button>
</div>

Categories