Get all 4-lettered words Regex - javascript

To get all 4 lettered words delimited by any I have written the following code:
function select() {
var html = document.getElementById('p').innerHTML;
var fourLettered = html.match(/[^a-zA-Z|^$][a-zA-Z]{4}[^a-zA-Z|^$]/g) || [];
document.getElementById('other').innerHTML = fourLettered.join('<br>');
}
p {
background-color: #eee;
}
.red {
color: red;
}
<p id="p" contenteditable="true">This is <i>a</i> <span class="red">paragraph</span> <b>with</b> lots of markup and-lots-of letters;with?four char</p>
<p id="other"></p>
<button onclick="select()">SELECT</button>
However, I am unable to get the 4 letter words at the start or end of the p tag i.e. This & char in this case.
Also the markup /span> is getting selected.
How can this problem be solved?

Try this:
function select() {
var html = document.getElementById('p').textContent;
var fourLettered = html.match(/\b[a-zA-Z]{4}\b/g) || [];
document.getElementById('other').innerHTML = fourLettered.join('<br>');
}
p {
background-color: #eee;
}
.red {
color: red;
}
<p id="p" contenteditable="true">This is <i>a</i> <span class="red">paragraph</span> <b>with</b> lots of markup and-lots-of letters;with?four char</p>
<p id="other"></p>
<button onclick="select()">SELECT</button>

Related

how to get the <a>under the <p>

I'm trying to get the a tag under the specific p tag.
I have tried this but is not working. I am trying to change the CSS style of the link part to red color and came with a red dot line when hovering the line will become solid.
var font_8 = document.getElementsByClassName('font_8');var elements = font_8.getElementsByTagName('a');
html:
<p class="font_7" style="font-size:16px">text text text text<br>
<span style="text-decoration:underline">link link link</span>(text)</p>
<p class="font_8" style="font-size:16px">text text text text<br>
<span style="text-decoration:underline">link link link</span>(text)</p>
js:
<script>
const styles = {
textDecoration: 'none',
color: 'red',
borderBottom: '2px dotted currentColor',
}
function getElements() {
var font_8 = document.getElementsByClassName('font_8');var elements = font_8.getElementsByTagName('a');
var len = elements.length;
for (let i = 0; i < len; i++) {
Object.keys(styles).forEach((key)=>{
elements[i].style[key]=styles[key]
})
}
for (let i = 0; i < len; i++){
elements[i].addEventListener('mouseover', function() {
elements[i].style.borderBottom= '2px solid currentColor';
})
elements[i].addEventListener('mouseout', function() {
Object.keys(styles).forEach((key)=>{
elements[i].style[key]=styles[key]
})
})
}
}
getElements()
</script>
Using JavaScript just to learn, this is my solution with a query selector:
const styles = {
textDecoration: 'none',
color: 'red',
borderBottom: '2px dotted currentColor',
}
const normalStyle = 'dotted'
const hoverStyle = 'solid'
function applyStylesAndHover() {
// querySelectorAll allows you to basically use a CSS selector in your JS
const elements = document.querySelectorAll('.font_8 a');
elements.forEach((element) => {
Object.keys(styles).forEach((key) => {
element.style[key] = styles[key]
})
element.addEventListener('mouseover', function() {
element.style.borderBottomStyle = normalStyle;
})
element.addEventListener('mouseout', function() {
element.style.borderBottomStyle = hoverStyle;
})
})
}
applyStylesAndHover()
<p class="font_7" style="font-size:16px">
text text text text
<br>
<span style="text-decoration:underline">
link
</span>(text)
</p>
<p class="font_8" style="font-size:16px">
text text text text
<br>
<span>
link
</span>(text)
</p>
Although To style the <a> on hover you do not need JavaScript.
CSS is perfect for this:
.font_8 a { /* An <a> inside of an element with the class of font_8 */
color: red;
text-decoration: none;
border-bottom: 2px solid red;
}
.font_8 a:hover { /* An <a> that is being hovered inside of an element with the class of font_8 */
border-bottom-style: dotted;
}
<p class="font_7" style="font-size:16px">
text text text text
<br>
<span style="text-decoration:underline">
link
</span>(text)
</p>
<p class="font_8" style="font-size:16px">
text text text text
<br>
<span>
link
</span>(text)
</p>
One problem i found here is you are tring to get <a> using font_8.getElementsByTagName('a'); which will not work. u will need to assign id to the a tag and get it by using
var element = document..getElementsById('myAncor');
and To move it inside p tag u will need to append the element to font_8 using .appenChild().
edit:
sry i misunderstood ur question.
to do this with JS use
var element= font_8[0].children[1].children[0];
element.addEventListener(
// your core
)
or
var elements= document.querySelectorAll('.font_8 a');
//Your code
elements[i].addEventListener(
// your core
)

javascript select & highlight text in 2 blocks at the same time in textarea and div

javascript select & highlight text in one of the blocks and highlight the text same time in textarea and div
<div id="preview"></div>
when you select the text in textarea
my goal is when you select text in textarea or div block
show the highlighted text in both books at the same time
here is what need to look
here is my code
function showPreview()
{
var value = $('textarea').val().trim();
value = value.replace("<", "<");
value = value.replace(">", ">");
$('#preview').html(value);
}
::-moz-selection { /* Code for Firefox */
color: red;
background: yellow;
}
::selection {
color: red;
background: yellow;
}
#preview { width:410px;
border: solid 1px #999; padding:5px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows="10" cols="50" onInput="showPreview();">
product noun
Save Word
To save this word, you'll need to log in.
Log In
prod·​uct | \ ˈprä-(ˌ)dəkt \
Definition of product
1: the number or expression resulting from the multiplication together of two or more numbers or expressions
2a(1): something produced
especially : COMMODITY sense 1
(2): something (such as a service) that is marketed or sold as a commodity
b: something resulting from or necessarily following from a set of conditions
a product of his environment
3: the amount, quantity, or total produced
4: CONJUNCTION sense 5
</textarea>
<br/>
<hr/>
<div id="preview">
</div>
right now highlights only when you select, neet to highlight in both
thank you
let textarea = document.querySelector('textarea');
let target = document.querySelector('#preview');
let plainLine = '\n';
let htmlLine = '<br/>';
let pressed = false;
function textToHtml(text) {
return text.replace(new RegExp(plainLine, 'g'), htmlLine).replace(/\s\s/g, ' ').replace(/^\s/g, ' ');
}
function htmlToText(html) {
html = html.replace(new RegExp(htmlLine, 'g'), plainLine);
return $('<div>').html(html).text();
}
function highlight(text, from, to) {
let mark = text.slice(from, to);
if (mark) mark = `<mark>${mark}</mark>`;
return text.slice(0, from) + mark + text.slice(to);
}
function showPreview() {
let from = textarea.selectionStart;
let to = textarea.selectionEnd;
let content = highlight(textarea.value, from, to);
target.innerHTML = textToHtml(content);
}
$(textarea).on({
mousedown: () => pressed = true,
mouseup: () => pressed = false,
mousemove: () => pressed && showPreview(),
click: () => showPreview(),
blur: () => showPreview()
});
showPreview();
::-moz-selection { /* Code for Firefox */
color: red;
background: yellow;
}
::selection {
color: red;
background: yellow;
}
#preview {
width: 410px;
border: solid 1px #999;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows="10" cols="50" onInput="showPreview();">
product noun
Save Word
To save this word, you'll need to log in.
Log In
prod·​uct | \ ˈprä-(ˌ)dəkt \
Definition of product
1: the number or expression resulting from the multiplication together of two or more numbers or expressions
2a(1): something produced
especially : COMMODITY sense 1
(2): something (such as a service) that is marketed or sold as a commodity
b: something resulting from or necessarily following from a set of conditions
a product of his environment
3: the amount, quantity, or total produced
4: CONJUNCTION sense 5
</textarea>
<br/>
<hr/>
<div id="preview">
</div>
Here is a very basic example:
const preview = document.querySelector("#preview");
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
}
document.addEventListener("click", () => {
const selectedText = getSelectionText();
if (selectedText !== "") {
preview.innerHTML = preview.innerHTML.replaceAll(
selectedText,
`<mark>${selectedText}</mark>`
);
}
});
function showPreview() {
let value = document.querySelector("textarea").value.trim();
value = value.replace("<", "<");
value = value.replace(">", ">");
preview.innerHTML = value;
}
::-moz-selection {
/* Code for Firefox */
color: red;
background: yellow;
}
::selection {
color: red;
background: yellow;
}
#preview {
width: 410px;
border: solid 1px #999;
padding: 5px;
}
<textarea rows="10" cols="50" onInput="showPreview();">Lorem ipsum dolor, sit amet consectetur adipisicing elit.</textarea>
<br />
<hr />
<div id="preview"></div>

JavaScript for changing a <div> colour from a button press

I'm a little unsure why my code doesn't seem to be working when my html and JS code are within the same file. When the html and JS are separate, seems to be working fine. Can someone point out the error in my ways....I'm a newbie!!
HTML:
<div class="main">
<div class="light"></div>
<button onclick="chngCol()" id="burn">Burn!</button>
</div>
JavaScript:
chngCol() {
if(document.getElementByClass('light').style.background == "#00ffff")
{
document.getElementByClass('light').style.background = "#ffff00";
}
else if(document.getElementByClass('light').style.background == "ffff00")
{
document.getElementByClass('light').style.background = "#ff00ff";
}
else if(document.getElementByClass('light').style.background == "#ff00ff")
{
document.getElementByClass('light').style.background = "#00ffff";
}
}
CSS:
.light{
width: 50px;
height: 50px;
background-color:#00ffff;
}
All code is in the same document with the appropriate tags and however the error i'm getting in Chrome Console on the first { after calling chngCol.
There are a multitude of issues.
chngCol() { is not valid JS. Either function chngCol() { OR const chngCol = () =>
You need document.getElementsByClassName("light")[0] OR better, document.querySelector(".light")
You cannot read the background color of the element if it is not set in script first.
I think you meant to do this:
let cnt = 0;
const colors = ["#00ffff", "#ffff00", "#ff00ff"];
const chngCol = () => {
cnt++;
if (cnt >= colors.length) cnt = 0; // wrap
document.querySelector('.light').style.background = colors[cnt]; // use the array
}
document.getElementById("burn").addEventListener("click", chngCol);
.light {
width: 50px;
height: 50px;
background-color: #00ffff;
}
#burn {
width: 150px;
font-weight: 700;
}
<div class="main">
<div class="light"></div>
<button id="burn">Burn!</button>
</div>
The document.getElementByClass selector is an array selector. In order to select your element you should select the first element of the array.
Try this instead:
document.getElementsByClassName('light')[0].style.background

Broken Javascript Code

I'm trying to create a website where three things happen, but I am stuck.
(1) When the button “ADD” button is clicked it will create a new paragraph
and add it to the output. The contents of the paragraph should come from the text area that is below the [ADD] button.
(2) If the “delete” button is pressed I need to delete the first paragraph in the div.
(3) If the user tries to delete when there are no paragraphs, create an “alert" that says:"No Paragraphs to delete".
I got my JS to put each paragraph into the div, but I'm not really sure how to delete it... Any help would be much appreciated.
window.onload = function() {
var button = document.getElementById("add");
button.onclick = insertItem;
}
function insertItem() {
var added = document.getElementById("output");
var textToAdd = document.getElementById("input");
if (textToAdd.value != "") {
var newp = document.createElement("p");
newp.innerHTML = textToAdd.value;
added.appendChild(newp);
}
}
var deletebutton = document.getElementsByTagName("delete");
deletebutton.onclick = deleteItem;
function deleteItem() {
var output = document.getElementById("output");
var pars = output.getElementsByTagName("p");
if (pars.length > 0) {
output.removeChild(pars[0]);
}
}
#output {
border: blue 5px solid;
padding: 10px;
margin-bottom: 10px;
margin-top: 10px;
width: 50%;
}
#output p {
padding: 10px;
border: black 1px dashed;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js" type="text/javascript"></script>
<script src="task3.js"></script>
</head>
<body>
<h2> TASK 3 - Creating, Appending and Deleting Nodes in the DOM Tree </h2>
<p> Type in text below, click add to add as paragraph. <button id="add"> Add </button> </p>
<textarea id="input" rows="10" cols="60">
</textarea><br>
<button id="delete">Delete Last Paragraph</button>
<br><br>
<h2> Added Paragraphs </h2>
<div id="output">
</div>
</body>
</html>
You're fetching the delete button wrong. You're using getElementsByTagName instead of by id.
When deleting, you will probably delete the first <p> you have in your markup that doesnt belong to your output. To fix this you could simply fetch all children of your output div and remove the first one:
function deleteItem() {
let output = document.getElementById('output')
if (output.hasChildNodes()) {
let outputs = output.childNodes
outputs[0].remove()
}
}

Highlight the text in textarea with delay

I am trying to highlight the single line of text in <textarea> with time delay. And I am wondering if I can choose a different color? The thing I wanted is when I click on the first <button>, the first line is highlighted into blue, click on the second <button>, 1 second later, the second line is highlighted into blue, lastly click on the third <button>, 2 second later, the third line is highlighted into yellow. I noticed I have a bug that I clicked on the button 3 times then the highlight doesn't work, but it is okay for me, I just want to know how to make the time delay and highlight with a different color. Thank you very much.
$( document ).ready(function() {
var str = 'line 1\nline 2\nline 3\n';
var textNumChar = str.length;
$('#str').val(str);
startPosition = 0;
$(".lines").click(function() {
var tarea = document.getElementById('str');
for(i=startPosition;i<textNumChar;i++)
{
if(str[i]=='\n') {
endposition = i;
break;
}
}
tarea.selectionStart = startPosition;
tarea.selectionEnd = endposition;
startPosition = endposition+1;
});
});
#container {
float: left;
}
button {
width: 50px;height: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<div id="container">
<button class="lines" id="line1">line 1</button>
<br>
<button class="lines" id="line2">line 2</button>
<br>
<button class="lines" id="line3">line 3</button>
</div>
<textarea id="str" rows="6"></textarea>
You can use setTimeout() to set the delay in highlighting the text based on button id.
And ::selection css selector to style the portion of an element that is selected.
$( document ).ready(function() {
var str = 'line 1\nline 2\nline 3\n';
var textNumChar = str.length;
$('#str').val(str);
startPosition = 0;
$(".lines").click(function(e) {
var tarea = document.getElementById('str');
for(i=startPosition;i<textNumChar;i++)
{
if(str[i]=='\n') {
endposition = i;
break;
}
}
var time = 0;
var tar_id = e.target.id;
var colors;
if(tar_id == 'line1' ) { colors = 'red'; }
else if(tar_id == 'line2' ) { time = 1000; colors = 'blue'; }
else if(tar_id == 'line3' ) { time = 2000; colors = 'green'; }
setTimeout(function(){
tarea.selectionStart = startPosition;
tarea.selectionEnd = endposition;
startPosition = endposition+1;
$('body').addClass(colors);
}, time);
});
});
#container {
float: left;
}
button {
width: 50px;height: 30px;
}
.red ::selection {
color: red;
background: yellow;
}
.blue ::selection {
color: blue;
background: red;
}
.green ::selection {
color: green;
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<div id="container">
<button class="lines" id="line1">line 1</button>
<br>
<button class="lines" id="line2">line 2</button>
<br>
<button class="lines" id="line3">line 3</button>
</div>
<textarea id="str" rows="6"></textarea>

Categories