Create a sentence containing keywords with a specific CSS with JavaScript - javascript

I would like to form a sentence. However, in this sentence there are keywords that contain a specific CSS, according to a word dictionary contained in a JSON.
I don't know how to take into account the CSS of dictionary words and the rest of my sentence to display it correctly.
For example, I get a sentence with:
I have a problem with my network cable....
Problem being in my dictionary in a JSON file I want it to get a specific CSS. Problem should appear in red.
I can only display keywords. I don't see how to reconstruct my sentence.
for (let i = 0; i < features.length; i++) {
for (let j = 0; j < newDataLime.length; j++) {
if (features[i] === newDataLime[j].label) {
console.log(newDataLime[j].rgba);
spanCounter ++
// Max 12 span by each line for ver
if(spanCounter == 12){
spanCounter = 0;
}
fieldText.innerHTML = fieldText.innerHTML + `<span class="verbatim-dashboard__text__lime hide" style="background-color: ${newDataLime[j].rgba};">${features[i]}</span>`;
}
}
}
Features is a table that contains all the words in my sentence cut to each space. So it contains for our example ["I", "Have", "Problem" ... etc.]
And the variable newDataLime contains the keywords of the dictionary.
How can I correctly form my sentence?
I hope I have been clear enough. Thank you in advance!

You should try to replace the word in your sentence array, with the stylized word.
And then, when your array is fully computed, you'll be able to put it in any DOM element :
for (let i = 0; i < features.length; i++) {
for (let j = 0; j < newDataLime.length; j++) {
if (features[i] === newDataLime[j].label) {
console.log(newDataLime[j].rgba);
spanCounter++
// Max 12 span by each line for ver
if (spanCounter == 12) {
spanCounter = 0;
}
features[i] = `<span class="verbatim-dashboard__text__lime hide" style="background-color: ${newDataLime[j].rgba};">${features[i]}</span>`;
}
}
}
fieldText.innerHTML = features.join(" ");

Related

Any alternative way of using this .charAt()?

I have a problem, when I used input[index] in the statement the reverse word didn't match the value of inputString. But this works in C#. When I try it in JavaScript is not working. I want to learn what are the other alternative way of .char() method. Can anybody solve my problem?
strReverse = "";
input = document.getElementById("inputValue").value;
i = input.length;
for(var j = i; j >= 0; j--) {
strReverse = strReverse + input.charAt(j); // i used input[index]
}
If you wish to use input[index] instead of input.charAt() then you need to address the issue that you are setting i = input.length;
So when you enter your loop for the first iteration, j will be equal to i. Meaning that you are trying to access the character at the index equal to the length of the string (when you do input[j]). However, as arrays and string indexing starts at zero in javascript (and in most languages), there is no index at i (the length of the string), but, there is an index at i-1, which will give the last character in the string. Thus, if you want to reverse your array using input[j] you need to start j in your for loop as j = i - 1.
Take a look at the snippet for a working example:
strReverse = "";
input = "level";
i = input.length;
for(var j = i-1; j >= 0; j--) {
strReverse = strReverse + input[j]; // i used input[index]
}
if(strReverse === input) {
alert(input +" is a palindrome!")
} else {
alert(input +" is not a palindrome!");
}

Javascript, take inputted string and print all possibilities

I've been searching for ours all over the web, including here for a way to solve this project I have for homework this week. To answer your question, the professor gave us a book that in no way connects with the homework so my textbook has been all but useless. I am very new to Javascript and don't even know where to begin with this project.
Project: "Write a JavaScript function that generates all combinations of an inputted word."
Example: "dog" would print: dog dgo god gdo odg ogd
I kinda wrote out the steps I need the code to make:
Ask user for a string. (i guess using some sort of input box but IDK which to use.)
Pass string to a function.
Function breaks the string into letters.
stores letters in an array.
Finds all combinations of stored array letters.
prints combinations in inner HTML.
Like I said I am very new to JS and so please explain any answers and feel free to ask questions and I'll do my best to answer them quickly.
The code i've tried:
function combo() {
var string = prompt("Please Enter a String", "Dog");
var strArr = string.split("");
var temp = "";
for (var i = 0; i < strArr.length; i++) {
temp = strArr[i];
console.log(temp);
for (var j = i + 1; j < strArr.length; j++) {
temp += strArr[j];
console.log(temp);
}
}
<button onclick="combo()">Click Me!</button>
<p id="demo"></p>
Like I said most of this is just what I could find online because I don't fully understand the concepts.
Edit: does anyone have an example of how I could send the input from the user to the function?
Using the answer found in this CodeReview question, the following will work fine:
function generateAnagrams(word)
{
if (word.length < 2)
{
return [word];
}
var anagrams = [];
var before, focus, after, shortWord, subAnagrams, newEntry;
for (var i = 0; i < word.length; i++)
{
before = word.slice(0, i);
focus = word[i];
after = word.slice(i + 1, word.length + 1);
shortWord = before + after;
subAnagrams = generateAnagrams(shortWord);
for (var j = 0; j < subAnagrams.length; j++)
{
newEntry = focus + subAnagrams[j];
anagrams.push(newEntry);
}
}
return anagrams;
}
document.getElementById('btn_go').onclick = function()
{
var words = generateAnagrams(document.getElementById('input_word').value);
document.getElementById('output').value = words.join("\n");
}
input,
textarea {
display: block;
margin-bottom: 20px;
width:60%;
}
textarea {
height: 200px;
}
<input id="input_word" placeholder="Input your word here" />
<textarea id="output"></textarea>
<button id="btn_go">
Go!
</button>

Printing in Javascript

i have a question that seems basic but i can't seem to figure it out.
Write a program that takes the value of a variable called “input” (declared as any whole number at the top of your program) and outputs a square made of asterisks () as large as the number (input). For example, if the “input” is declared with the value 5, your program would display a square made of 25 asterisks() – ie ; 5 asterisks () high, by 5 asterisks () long.
The code i've come up with so far is below. I don't really understand how to make a string continuously print. If i did star = i then it turns into numbers and will print the numbers. So how do i make it so they connect? I also can't figure out where i should put the new line. console.log(star "\n"); gives me an error. Please help :)
var input = 2;
var star = "*";
var i = 0;
do {
console.log(star);
i++;
} while (i < input);
You can use String.repeat() (ES6 only) along with \r\n to add new line
var input = 5,
star = "*",
str = [],
i = 0;
do {
str.push( Array(input).join(star) ); // use array(length).join
i++;
} while (i < input);
str = str.join("\r\n"); // add breaklines
console.log(str);
console.log Will output a single line to the console containing whatever you pass it as an argument. You are trying to print a line of n asterisks n times.
The first step you should take is constructing the string of asterisks. You can concatenate a string to another with the + operator:
var input = 2;
var star = "*";
var line = "";
for(var i = 0; i < input; i++) {
line = line + star;
}
Once you have constructed line you can then print it n times:
for(var i = 0; i < input; i++) {
console.log(line);
}
Hint: You could create an empty array and then create a loop ending at your wanted number of asterisks after which you will join all the members of the array together. (Writing the code here wouldn't help you much since you mentioned it's an homework).
You could approach this in two ways. If we call your input value n, then we can log either n strings each consisting of n stars, or we can log a single string, containing (n * n) stars, with line breaks after every nth star.
Below is an example of a function that could do this task.
function stars (input) {
var output = ''
for (var i = 0; i < input; i++) {
for (var j = 0; j < input; j++) {
output += '*'
}
output += '\n'
}
return output
}
You can use the repeat-function to print a character multiple times.
var input = 2;
var star = "*";
var i = 0;
while(i++ < input){
console.log(star.repeat(input));
}
This repeats the * character input times in input lines.

How to remove the unnecessary html after appending?

var split = $('.split-locations').text().split('\n');
for (var i = 0; i < split.length; i++) {
$('.split-locations').append("<pre>"+split[i]+"</pre>");
}
<div class="split-location">
Singapore
USA
Aussie
</div>
On profile, the user type with enter for each address, but the problem is when it is saved, the addresses would be displayed on the webpage as:
Singapore USA Aussie
<pre>Singapore</pre>
<pre>USA</pre>
<pre>Aussie</pre>
I am not sure why the text (Singapore USA Aussie) is still there. Only wanted to display:
<pre>Singapore</pre>
<pre>USA</pre>
<pre>Aussie</pre>
How to remove the first line before <pre> bunch? Or how to replace text with pre bunch?
Update
One more thing: how to print first array outside loop because need to display first one outside loop and then put the rest of array inside accordion?
Here the code is: for you to understand what I am trying to do. see the comment.
var location = $('.split-locations');
var split = $('.split-locations').text().split('\n');
location.empty();
//need to print first location
location.append('<div class="accordion-location">');
for (var i = 0; i < split.length; i++) {
//print remaining location after minus first location
location.append("<pre>"+split[i]+"</pre>");
}
location.append('</div>');
});
You need to empty the container element before appending the pre nodes. Try this.
var split = $('.split-locations').text().split('\n');
$('.split-locations').empty();
for (var i = 0; i < split.length; i++) {
$('.split-locations').append("<pre>"+split[i]+"</pre>");
}
You need to clear out the location:
var split = $('.split-locations').text().split('\n');
$('.split-locations').empty();
for (var i = 0; i < split.length; i++) {
$('.split-locations').append("<pre>"+split[i]+"</pre>");
}
Update:
var $el = $('<div class="accordion-location"></div>');
for (var i = 0; i < split.length; i++) {
$el.append("<pre>"+split[i]+"</pre>");
}
location.append($el);

Search Box Function Not Eliminating Correct Value

I am trying to make a simple website where the user types input into a search box, and every time a key is press, their input is compared against the first row of a 2 dimensional array which checks for character matches. If the character they input doesn't match anything, I want it to remove that specific bucket of the array. I have attempted to write basic code for this I thought would work, and have it up at the demo site linked. (Sorry I am just using a free host and havn't optimized the equation table at all so bear with it)
http://fakefakebuzz.0fees.net/
As you can see, the function is not eliminating the appropriate table rows. For example, typing "A" should not eliminate the "Average Current Equation" row because the first letter of that is A, which means matches should not = 0.
I have been looking through this code all morning, and cannot find where I went wrong. I also want to stick to vanilla js.
Any help?
Thanks so much.
I just debugged your code, and the function you use is narrowTable. first remove onkeypress from body node
<body onload="printTable()" onkeypress="narrowTable()">
and add onkeyup instead to you input, like this:
<input type="search" name="equationSearch" id="equationSearch"
placeholder="Equation Search" autofocus="" onkeyup="narrowTable()">
because when you use onkeypress the key value hasn't been added to the input box and your input value has no value in your function, which is:
function narrowTable() {
var newTableContent = "";
var matches = 0;
var input = document.getElementById("equationSearch").value;
//input has no value
for (var i = 0; i < tableData.length; i++) {
for (var j = 0; j < tableData[i][0].length; j++) {
if (input == tableData[i][0].charAt(j)) {
matches++;
}
}
if (matches == 0) {
tableData.splice(i, 1);
}
matches = 0;
}
for (var i = 0; i < tableData.length; i++) {
newTableContent += "<tr><td>" + tableData[i][0] + "</td><td>" + tableData[i][1] + "</td></tr>";
}
document.getElementById("table").innerHTML = newTableContent;
}
the other problem your code has is after printing your table, your tableData variable has changed because you have removed some of indexes. you should reset the tableData to its original value or you can do:
function narrowTable() {
//create a copy of your original array and use currenttableData instead
var currenttableData = tableData.slice();
var newTableContent = "";
var matches = 0;
//your code
}
the other problem here is the way you search for your input value:
for (var j = 0; j < tableData[i][0].length; j++) {
if (input == tableData[i][0].charAt(j)) {
matches++;
}
}
if (matches == 0) {
tableData.splice(i, 1);
}
you can easily do this, instead:
if(tableData[i][0].search("input") == -1){
tableData.splice(i, 1);
}
First, to check if a string is a substring of another string, you can use indexOf. It will return -1 if the string is not found in the other string.
Second, you shouldn't alter the array while you are still looping through it, unless you make sure to alter the counter variable (i in this case) appropriately.
var dataToRemove = [],
i;
for (i=0; i<tableData.length; i++) {
if(tableData[i][0].indexOf(input) == -1) {
// add the index to the to-be-removed array
dataToRemove.push(i);
}
// remove them in reverse order, so the indices don't get shifted as the array gets smaller
for(i = dataToRemove.length - 1; i >= 0; i--) {
tableData.splice(i, 1);
}
dataToRemove = [];
for (i=0; i<tableData.length; i++) {
newTableContent += "<tr><td>" + tableData[i][0] + "</td><td>" + tableData[i][1] + "</td></tr>";
}
I haven't tested this code, but it should at least give you a better idea of how to make this work.

Categories

Resources