Replacing innerText with an innerHTML - [object HTMLSpanElement] error - javascript

Solved:
I receive Chinese content from an API and use a special font for this language. But some names in this content have a-zA-Z0-9 letters and for them I want to use "Montserrat" font. Now I write a span around these words / numbers:
打扰一下。打扰一下。[object HTMLSpanElement] [object HTMLSpanElement] 打扰一下。打扰一下。
This is what I want:
<div class="vce-post-description--excerpt">
<p>打扰一下。打扰一下。<span style="font-family: Montserrat;">51612</span> <span style="font-family: Montserrat;">Hello</span> 打扰一下。打扰一下。</p>
</div>
Here the solution - JS part:
<script>
document.addEventListener("DOMContentLoaded", () => {
const regex = /[0-9A-Za-z]+/g;
var textElements = document.querySelectorAll(".vce-post-description--title a, .vce-post-description--excerpt");
for (var i = 0; i < textElements.length; i++) {
if (textElements[i].textContent.match(regex)) {
var foundString = textElements[i].textContent.match(regex).toString();
//console.log("Changing Words: "+foundString);
let foundArray = foundString.split(",");
foundArray.forEach(changeInnerText);
}
}
function changeInnerText(item) {
addElement = document.createElement('span');
addElement.style.fontFamily = "Montserrat";
addElement.style.visibility = "visible";
addElement.textContent = item;
//console.log('New Style: '+addElement.outerHTML);
var regex = new RegExp(item, "g");
tempHTML = textElements[i].innerHTML.replace(regex, addElement.outerHTML);
textElements[i].innerHTML = tempHTML;
}
})
</script>
And here is the JSFiddle.

Related

change color of words within an array

if i have an javascript array of words
var keywords = ["select","from","where","mars"];
and HTML element holding a text
<div id="mytext">Hello from planet mars</div>
How to use javascript to color in orange any word found in this element mytext of words list in the array keywords !
Here is one way to do it:
var keywords = ["select", "from", "where", "mars"];
let originalText = document.querySelector("#mytext").innerText
for (const word of keywords) {
originalText = originalText.replace(new RegExp(word, "g"), `<span class="orange">${word}</span>`)
}
document.querySelector("#mytext").innerHTML = originalText
.orange {
color: orange;
}
<div id="mytext">Hello from planet mars</div>
we are iterating over the keywords and replacing the innerHTML with a new content where we would wrap mentions of the keyword with a markup that would give it a color.
<html>
<head></head>
<body>
<div id="mytext">Hello from planet mars</div>
<script>
var keywords = ["select","from","where","mars"];
mytext=document.getElementById("mytext");
len=keywords.length;
for(i=0;i<len;i++){
mytext.innerHTML=mytext.innerHTML.replaceAll(keywords[i],"<span style='color:orange;'>"+ keywords[i] +"</span>");
}
</script>
<body>
You can use this code and replace the orange color with the color you want
var keywords = ["select","from","where","mars"];
mytext=document.getElementById("mytext");
len=keywords.length;
for(i=0;i<len;i++){
mytext.innerHTML=mytext.innerHTML.replaceAll(keywords[i],"<span style='color:orange;'>"+ keywords[i] +"</span>");
}
<html>
<head></head>
<body>
<div id="mytext">Hello from planet mars</div>
<body>
</html>
var keywords = ["select","from","where","mars"];
let div = document.getElementById('mytext')
let text_content = div.textContent.split(' ')
let html = text_content.map(e => {
return keywords.includes(e) ? `<span class='orange'>${e}</span>` : e })
div.innerHTML = html.join(' ')
.orange{
color:orange;
}
<div id="mytext">Hello from planet mars</div>
you can try
var keywords = ["select","from","where","mars"];
const el = document.querySelector('#mytext');
keywords.map(kw => el.innerText = el.innerText.replace(new RegExp(kw, 'g'), '<span style="color: oragne">' + kw + '</span>'))
el.innerHTML = el.innerText
Yet another regex option, but creating a single regex out of the array resulting in a single query/innerHTML assignment.
const keywords = ["select","from","where","mars"];
const mytext = document.getElementById('mytext');
mytext.innerHTML = mytext.textContent.replace(
new RegExp(`\\b${keywords.join('\\b|\\b')}\\b`, 'g'),
(match) => `<span class='orange'>${match}</span>`
);
.orange {
color: orange;
}
<div id="mytext">Hello from planet <span class="where">mars</span>, select from fromage mars.</div>
The resulting regex
/\bselect\b|\bfrom\b|\bwhere\b|\bmars\b/g

How to put the value of a function inside the template literal?

Im making a comment system and is required to put the stars inside of template literal with the purpose that the number of stars stay next to the name of the person.
Until now the value is showing me "undefined"
screenshoot screenshot comment system
this is the javascript code
const txtNombre = document.getElementById("text-nombre");
const txtParrafo = document.getElementById("text-area");
const boton = document.getElementById("btnAgregar");
const listado = document.getElementById("contenedor-filas");
const radio = document.getElementsByName("rate");
boton.addEventListener("click", agregarALista);
function agregarALista() {
let nombre = txtNombre.value;
var valor = txtParrafo.value;
const elHtml = document.createElement("div");
elHtml.innerHTML = `
<div class="row" id="fila-segunda">
<div class = "col-6">
${nombre}
</div>
<div class = "col-6">
${estrellitas()}
</div>
</div>
<div class="row" id="fila-tercera">
<div class = "col">
${valor}
</div>
</div>
`;
listado.appendChild(elHtml);
txtNombre.value = "";
txtParrafo.value = "";
}
let estrellitas = function() {
radio.forEach(function(elementos) {
if (elementos.checked) {
estrellas = document.createElement("h3");
estrellas.setAttribute("class", "stars");
let s = "";
for (i = 0; i < elementos.value; i++) {
s += "★";
}
estrellas.textContent = s;
listado.appendChild(estrellas);
}
});
}
Your function estrellitas() is missing a return statement and will therefore return undefined. Otherwise, your syntax for including function return values in string template literals is correct:
let x = (a, b) => a > b;
let a = 10, b = 20;
console.log(`${a} is greater than ${b}? ${x(a, b)}`);

How to skip converting element text

i want output text oldnames not changes if user insert text 'false'
for example:
user input text "false toni" in textbox.
and i want output still "false toni"
why my code still changes text "toni" with "rina"?
<script type="text/javascript" charset="utf-8">
String.prototype.replaceArr = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
}
function test() {
var x = document.getElementById("myText").value;
var oldNames = ['toni','rian'];
var newNames = ['rina','susi'];
if (oldNames== 'false ' + oldNames){
document.getElementById("check").innerHTML = x.replaceArr(oldNames, oldNames);
}else{
document.getElementById("check").innerHTML = x.replaceArr(oldNames, newNames);
}
}
</script>
<body>
ENTER TEXT: <br>
<textarea name="kata_cari" id="myText" style="width:100%; height:100px;"></textarea>
<br>
<input type="button" onclick="test();" value="Check!">
<br>
<p id="check"></p>
</body>
UPDATE:
Improve the question:
Trying enter text "My name is rian and my name is false toni" .
Posible to make output "rian" still change to "susi"?
use includes x.includes(value) to check whether the text area value contains a word that you want to replace . if it contains false then your oldnames not get changed.
If you are using IE then use x.indexOf(value)>0 instead of x.includes(value)
http://www.w3schools.com/jsref/jsref_includes.asp
<script type="text/javascript" charset="utf-8">
String.prototype.replaceArr = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace);
}
return replaceString;
}
function test() {
var x = document.getElementById("myText").value;
var oldNames = ['toni', 'rian'];
var newNames = ['rina', 'susi'];
oldNames.forEach(function(value, index) {
/*if (x.includes('false '+value)){
var oldNames1=['false '+value];
x = x.replaceArr(oldNames1, oldNames1);
}*/
if (x.includes(value)) {
var oldNames1 = [value];
x = x.replaceArr(oldNames1, newNames[index]);
newNames1 = ['false ' + newNames[index]];
oldNames1 = ['false ' + value];
x = x.replaceArr(newNames1, oldNames1);
}
});
document.getElementById("check").innerHTML = x;
}
</script>
<body>
ENTER TEXT:
<br>
<textarea name="kata_cari" id="myText" style="width:100%; height:100px;"></textarea>
<br>
<input type="button" onclick="test();" value="Check!">
<br>
<p id="check"></p>
</body>
You false checking condition is wrong, you can do it using substr:
if (x.substr(0, 6) === 'false ') {
// The string starts with false
} else {
}
You can find more details on the substr from MDN.
UPDATE: As mentioned in the comment same can be done via startsWith and this is a better approach.
if (x.startsWith('false ')) {
// The string starts with false
} else {
}
try this. Compare array values instead of array.
<script type="text/javascript" charset="utf-8">
String.prototype.replaceArr = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
}
function test() {
var x = document.getElementById("myText").value;
var oldNames = ['toni','rian'];
var newNames = ['rina','susi'];
if (x.indexOf('false') > -1 ){
document.getElementById("check").innerHTML = x.replaceArr(oldNames, oldNames);
}else{
document.getElementById("check").innerHTML = x.replaceArr(oldNames, newNames);
}
}
</script>
<body>
ENTER TEXT: <br>
<textarea name="kata_cari" id="myText" style="width:100%; height:100px;"></textarea>
<br>
<input type="button" onclick="test();" value="Check!">
<br>
<p id="check"></p>
</body>

Removing a range starting occurrence with specified place

I need to define the text area to delete from 4th occurrence of (_) and preserve the extension.
before 12_345_678_900_xxxxxxxxxxxxxxx.jpg after 12_345_678_900.jpg,
before 34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg
after 34_567_890_123.jpg
Is it possible?
One solution is to find the nth occurence and then use substring.
var one='12_345_678_900_xxxxxxxxxxxxxxx.jpg'; // 12_345_678_900.jpg
function nth_occurrence (string, char, nth) {
var first_index = string.indexOf(char);
var length_up_to_first_index = first_index + 1;
if (nth == 1) {
return first_index;
} else {
var string_after_first_occurrence = string.slice(length_up_to_first_index);
var next_occurrence = nth_occurrence(string_after_first_occurrence, char, nth - 1);
if (next_occurrence === -1) {
return -1;
} else {
return length_up_to_first_index + next_occurrence;
}
}
}
console.log(one.substring(0,nth_occurrence(one,'_',4))+one.substring(one.indexOf('.')));
Sure, split by "_" and then join back the data you want:
var str = "12_345_678_900_xxxxxxxxxxxxxxx.jpg";
str = str.split("_").slice(0,4).join("_") + "."+ str.split(".").slice(-1)
console.log(str)
Regular Expressions are great for this sort of scenario:
const data1 = '12_345_678_900_xxxxxxxxxxxxxxx.jpg'
const data2 = '34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg'
const re = /^([^_]+_[^_]+_[^_]+_[^_]+).*(.jpg)$/;
var test1 = data1.replace(re, '$1$2');
var test2 = data2.replace(re, '$1$2');
Try it out: https://jsfiddle.net/648xt3qq/
There are probably a few different regular expression approaches that would get the job done
Maybe this works for you:
function clean() {
var el = document.getElementById('area');
el.value = el.value.replace(/^(.*?_.*?_.*?_.*?)(_.*?)(\..*?.*)$/gmi, '$1$3');
}
<form action="">
<textarea cols="50" rows="4" id="area">12_345_678_900_xxxxxxxxxxxxxxx.jpg
34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg</textarea><br />
<input type="submit" onclick="clean(); return false;" />
</form>

Reading textbox input and putting in one of two boxes javascript

I am trying to allow the user to enter 1 letter in a text box, and then the letters gets put into 1 of 2 boxes. This is for a hangman game, so it is going to divide the letters based on whether or not it is in the word. Here's my code. Hopefully someone can help me. I'm new to javascript! I've done a ton of googling, but to little avail.
var words = ['dog', 'computer', 'cat', 'monkey', 'human'];
var wordForGuess = chooseWord();
var wordLength = wordForGuess.length;
function chooseWord () {
return words[Math.floor(Math.random() * words.length)];
}
function writeWord()
{
var textarea = document.getElementById('textBox').value;
for (var x = 0; x<wordLength; x++)
{
if (textarea === wordForGuess.indexOf(x))
{
document.getElementById('correctLetters').value = textarea;
}
else
{
document.getElementById('incorrectLetters').value = textarea;
}
}
}
As well as the HTML for my textbox
<div id = 'letterInput'>
</div>
<input type = 'text' id = 'textBox' onkeyUp="writeWord()"/>
<div id = 'correctLetters'>
</div>
<div id = 'incorrectLetters'>
</div>
I think you have a few mistakes, including iterating over your characters in your chosen word and using the index of that iteration instead of just checking the value from the input box. I also think you should reset the value on each keyup. I also moved your onkeyup event out of the HTML into JavaScript, I think maybe in your case the JavaScript hadn't loaded yet but it's hard to tell from your example.
<div id = 'letterInput'>
</div>
<input type = 'text' id = 'textBox' />
<br/>
Correct:
<div id = 'correctLetters'>
</div>
<br/>
Incorrect
<div id = 'incorrectLetters'>
</div>
Here's the JavaScript with some fixes:
var words = ['dog', 'computer', 'cat', 'monkey', 'human'];
var wordForGuess = chooseWord();
var wordLength = wordForGuess.length;
function chooseWord () {
return words[Math.floor(Math.random() * words.length)];
}
function writeWord() {
var input, textarea;
input = document.getElementById('textBox')
textarea = input.value;
input.value = "";
console.log("writing word", textarea);
if (wordForGuess.indexOf(textarea) !== -1) {
document.getElementById('correctLetters').innerText += textarea;
} else {
document.getElementById('incorrectLetters').innerText += textarea;
}
}
document.getElementById("textBox").onkeyup = writeWord;
Here's a jsfiddle with this code.

Categories