I am developing web portal for ASR (Automatic speech recognition). As you all know that ASR won't give the 100% correct result. The main reason of getting wrong result are speaking behavior of person, noise, style of speaking, voice intensity, homophones (buy, bye. cite, site) etc. I am planning to do post processing by using web portal. I defined textarea where I get the recognized text. If user found that wrong word in text area then he will double click on wrong word in textarea and after word selection in same place display similar word pronunciation option (Similar pronunciation words are stored in text file. one line contains same pronunciation words) exa. If user selected word "sad" then in option he will get "sad, mad, bad" etc. I have created text file which contains following lines
sad, mad, bad
hero, zero
site, cite
buy,bye
If user select word "site" then he will get "site, cite" in textarea and finally user will select his correct word. Indirectly I am searching word in text file and if word found in text file then copy whole line and display as option in textarea (like google display's search options after entering text)
I wrote small code but getting failed to done all functionalities. My text file is locally stored.
<textarea name="text" id="textdata" rows="7" cols="79" wrap="soft" maxlength="4000" style="overflow:auto; resize:none; font-size: 17pt; font-family:"Times New Roman"
onselect="populateList(this.value)" > </textarea>
<script>
function populateList(val)
{
// alert("Entered populateList ");
var textComponent = document.getElementById('textdata');
var selectedText;
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos);
alert("Selected word : "+selectedText);
dic(selectedText);
}
</script>
<script>
$.get("http://localhost/english/master.txt",function(returnedData) {
$("#element").text(returnedData);
},"text/plain");
</script>
<script>
var text = $("#element").text();
var words = text.split(" ");
var dictionary = new Array();
for(var i=0; i < words.length; i++) {
dictionary[i] = words[i];
alert("dictionary elements are :"+dictionary[i]);
}
</script>
<script>
function dic(word) {
alert("Word passed for searching :"+word);
// var dictionary = new Array("Java","Python","Swift","HTML","PHP");
// This line is unnecessary; use the dictionary var already created.
var flag = 0;
for(var i = 0; i < dictionary.length; i++) {
if(dictionary[i] == word) {
document.getElementById("result").innerHTML = "Element Found";
flag = 1;
alert("Element found ");
break;
}
if(i == dictionary.length - 1) {
document.getElementById("result").innerHTML = "Element Not Found";
alert("Element not found ");
}
}
}
</script>
I am new in website development.
I've solved your problem, but I'm not using txt file, but json (because of CORS problem in fiddle), but if you create txt file it will work same. One line for one prompt words in file.
function populateList(val)
{
let textComponent = document.getElementById('textdata');
let tooltip = document.getElementById('tooltip');
let selectedText;
let startPos = textComponent.selectionStart;
let endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos);
fetch('https://api.myjson.com/bins/z9wr6').then(data=>data.json()).then(data=>{
let text = data.result.split('\n').reduce((acc,e)=>{
acc.push(Array.prototype.concat.call([],e.split(' ')))
return acc
},[]);
text.forEach(e=>{
if(e.find(ele=>ele===selectedText)){
tooltip.innerHTML = e.join(', ')
}
})
})
}
And working fiddle: https://jsfiddle.net/bfx8jdgh/
Related
I created a spreadsheet to keep track of all the videos uploaded by the YouTubers I follow. Then, I created a script to be executed from the console that lists all the videos of that user. I store the list in a variable, and then I log it, select it, and copy it to the clipboard, but I'd like to copy it automatically every time I run the script. The problem is that the text is not inside an element (like a div, or textarea), so I can't use either window.navigator.clipboard or document.execCommand('copy').
Is there a way to do that?.
Thanks & greets from Argentina (Hope it is from England someday).
IDsign4U (Marcelo Miguel Bazan).
This is the code I use (open the videos tab in any channel and try it):
console.clear();
console.log("Título + Duración + Estado + URL en Subscripciones (sin número de orden)");
var domains = "";
var i = "";
var text = "";
var title = "";
var duration = "";
var hours = "";
var link = "";
var video = "";
var textDuration = "";
var hoursCheck = "";
var finalDuration = "";
var finalTitle = "";
domains = document.getElementsByTagName('ytd-grid-video-renderer')
for (i = 0; i < domains.length; i++)
{title = domains[i].getElementsByTagName('h3');
duration = domains[i].getElementsByTagName('span');
link = domains[i].getElementsByTagName('a');
textDuration = duration[0].innerText.trim();
hoursCheck = "";
hoursCheck = textDuration.length > 5 ? "0": "00:";
finalDuration = hoursCheck + textDuration + "\t" + "P" + "\t";
finalTitle = title[0].innerText + "\t";
url = "https://www.youtube.com" + link[0].attributes['href'].value;
video = video + finalTitle + finalDuration + url + "\n";}
console.log(video);
Why shouldn't you be able to use navigator.clipboard? It works fine while providing variables to copy to clipboard.
document.getElementById("copy").addEventListener("click", async () => {
const text = "Text copied to the clipboard"
await navigator.clipboard.write(text)
})
<button id="copy">
Copy to clipboard
</button>
When you say "from the console", do you mean the browser console? If so, there's a built-in global copy function (not window.copy, just copy).
Yes!! Thank you Zac (and wOxxOm and Jannis Ioannou) for the answer.
It's just a matter of deleting the, for me, weird DOM element with the ID 'copy' to be able to use the copy function in the console.
Thanks & greets from Argentina (Hope it is from England someday).
IDsign4U (Marcelo Miguel Bazan).
What i have done:
function makeBold(strings) {
var myHTML = document.getElementsByTagName('body')[0].innerHTML;
myHTML = myHTML.replace(strings, '<b>' + strings + '</b>');
document.getElementsByTagName('body')[0].innerHTML = myHTML
}
this code works only for the paces where the texts are free from ant tags
Eg: <p class="ClassName">Some free text without any inner html elements</p>
But for sentences below this the above javascript function is not giving any result
Eg sentence which are not working:
<p class="Aclass"><span class="char-style-override-1">Starting from here, </span><span class="char-style-override-2">text resumes after the span tag</span><span class="char-style-override-1">. again text resumes.</span></p>
What I need
i need a functionality to make the above text bold when i pass that text into my js function. and by text i mean only
Starting from here,text resumes after the span tag. again text resumes.
when i call the above mentioned jas function like this
makeBold('Starting from here,text resumes after the span tag. again text resumes.');
nothing happens, the entire sentence does not gets bold nothing happens, because the js function only looks for the occurrence of that string and makes it bold, in my second example the text is mixed with html tags
so that the above mentioned text will get bold when i call my makebold function.
Please note that i dont have the id for the <p> , what i have is a couple of random strings stored in my db and load a couple of webpages, while doing so i want to bold the sentence/text from the webpage if is matches with my passed string from db
While doing my research i got a code to highlight text given to a js. this js function will select the exact text in the html page which is passed to the js function.
the second eg also works for this code. i.e i can select the exact string from the example by passing it to the function.
function selectText(text) {
if (window.find && window.getSelection) {
document.designMode = "on";
var sel = window.getSelection();
sel.collapse(document.body, 0);
while (window.find(text)) {
document.getElementById("button").blur();
document.execCommand("HiliteColor", false, "yellow");
sel.collapseToEnd();
}
document.designMode = "off";
} else if (document.body.createTextRange) {
var textRange = document.body.createTextRange();
while (textRange.findText(text)) {
textRange.execCommand("BackColor", false, "yellow");
textRange.collapse(false);
}
}
}
I tried to customize it so that instead of selecting the passed text, i tried to make it bold. but coudnt succed.
Please help me in getting this done. I am new to js.
I finally got a solution to your problem that works as you want it to (i. e. the function takes an arbitrary substring and marks anything that fits the substring bold while leaving the rest of the string untouched). If the string passed doesn't match any part of the string that you want to modify, the latter remains untouched.
Here goes (Beware: That JS section got really BIG!):
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test case for making arbitrary text bold</title>
<meta charset="UTF-8">
<script type="application/javascript">
// Takes two strings and attempts to intersect them (i. e. the end of p_str1
// must match the beginning of p_str2). The index into p_str1 is returned.
// If no intersection can be found, -1 is returned.
function intersectStrings(p_str1, p_str2)
{
var l_pos = -1;
do
{
l_pos = p_str1.indexOf(p_str2[0], l_pos + 1);
if(p_str1.substr(l_pos) == p_str2.substr(0, p_str1.length - l_pos))
// If the two substrings match, we found something. Return with the position.
break;
}
while(l_pos != -1);
return l_pos;
}
function makeBold(p_string)
{
var l_elem = document.getElementById('modify');
var l_html = l_elem.innerHTML;
var l_text = l_elem.innerText;
var l_aux = l_html.match(/<.+?>/g);
var l_here = l_text.indexOf(p_string);
var l_before;
var l_middle;
var l_behind;
if(typeof(p_string) != 'string')
throw "invalid argument";
// First of all, see whether or not we have a match at all. If no, we don't
// need to continue with this.
if(l_here == -1)
{
console.error('makeBold: Could not find desired substring ' + p_string + '! Stop...');
return;
}
// Take the plain text and split it into three distinct parts (l_middle is of
// interest for us here).
l_before = l_html.slice(0, l_here);
l_behind = l_html.slice(l_here + l_html.length);
l_middle = l_html.slice(l_here, l_here + l_html.length);
if(l_aux)
{
// If we have a set of markup tags, we need to do some additional checks to
// avoid generating tag soup.
let l_target = new Array();
let l_tag;
let l_nexttag;
let l_this;
let l_endpos = 0;
let l_in_str = false;
let l_start;
while(l_aux.length - 1)
{
l_tag = l_aux.shift();
l_target.push(l_tag);
l_nexttag = l_aux[0];
l_endpos = l_html.indexOf(l_nexttag, 1);
l_this = l_html.slice(l_tag.length, l_endpos);
l_html = l_html.slice(l_endpos);
// Skip the entire rigmarole if there are two adjacent tags!
if(l_tag.length == l_endpos)
continue;
if(!l_in_str)
{
if((l_start = l_this.indexOf(p_string)) != -1)
{
// If we find the entire passed string in a fragment of plain text, we can
// modify that, reassemble everything and exit the loop.
l_before = l_this.slice(0, l_start);
l_behind = l_this.slice(l_start + p_string.length);
l_middle = l_this.slice(l_start, l_start + p_string.length);
l_this = l_before + '<strong>' + l_middle + '</strong>' + l_behind;
l_target.push(l_this);
l_target.push(l_html);
l_html = l_target.join('');
console.info('makeBold: The passed string fit between two tags: Done!');
break;
}
// Take the possibility of having to scan across fragments into account. If
// that is the case, we need to piece things together.
if((l_start = intersectStrings(l_this, p_string)) != -1)
{
// Once we wind up here we have a partial match. Now the piecework starts...
l_before = l_this.slice(0, l_start);
l_middle = l_this.slice(l_start);
l_this = l_before + '<strong>' + l_middle + '</strong>';
l_target.push(l_this);
console.info('makeBold: Found starting point of bold string!');
l_in_str = true;
}
else
{
// Nothing to do: Push the unmodified string.
l_target.push(l_this);
}
}
else
if((l_endpos = intersectStrings(p_string, l_this)) == -1)
{
// We haven't arrived at the end position yet: Push the entire segment with
// bold markers onto the stack.
l_this = '<strong>' + l_this + '</strong>';
l_target.push(l_this);
}
else
{
// We have an end position: Treat this fragment accordingly, wrap everything up
// and exit the loop.
l_behind = l_this.slice(l_endpos + 1);
l_middle = l_this.slice(0, l_endpos + 1);
l_this = '<strong>' + l_middle + '</strong>' + l_behind;
l_target.push(l_this);
l_target.push(l_html);
l_html = l_target.join('');
console.info('makeBold: Found the end part: Done!');
break;
}
}
}
else
l_html = l_before + '<strong>' + l_middle + '</strong>' + l_behind;
l_elem.innerHTML = l_html;
}
</script>
</head>
<body>
<header><h1>Test case for making arbitrary text bold by using JavaScript</h1></header>
<main>
<p id="modify"><span class="char-style-override-1">Starting from here, </span><span class="char-style-override-2">text resumes after the span tag</span><span class="char-style-override-1">. again text resumes.</span></p>
</main>
<script type="application/javascript">
// makeBold('Starting from here, text resumes after the span tag. again text resumes.');
// makeBold('from here, text resumes');
// makeBold('resumes after the span');
makeBold('text resumes after the span tag');
</script>
</body>
</html>
Unfortunately this job couldn't be done with a short section, because you need to take various cases into account that need to be handled individually. The control logic that I have come up with addresses all these concerns.
See the annotations in the JS that I have made for details.
Hey :) I know a similiar question was asked before, but i just cant get it through. I want to create a method called something like makeMeSpaces, so my h2 text will have a space between each character.. and i might want to use it elsewhere aswell. I have this until now, from the logic point of view:
var text = "hello";
var betweenChars = ' '; // a space
document.querySelector("h1").innerHTML = (text.split('').join(betweenChars));
it also works pretty fine, but i think i want to do
<h2>Hello.makeMeSpaces()</h2>
or something like this
Thank you guys!
If you really want this in a 'reusable function,' you'd have to write your own:
function addSpaces(text) {
return text.split('').join(' ');
}
Then, elsewhere in code, you could call it like so:
var elem = document.querySelector('h2');
elem.innerHTML = addSpaces(elem.innerHTML);
Maybe this is what you want , not exactly what you showed but some what similar
Element.prototype.Spacefy = function() {
// innerText for IE < 9
// for others it's just textContent
var elem = (this.innerText) ? this.innerText : this.textContent,
// replacing HTML spaces (' ') with simple spaces (' ')
text = elem.replace(/ /g, " ");
// here , space = " " because HTML ASCII spaces are " "
space = " ",
// The output variable
output = "";
for (var i = 0; i < text.length; i++) {
// first take a character form element text
output += text[i];
// then add a space
output += space;
};
// return output
this.innerHTML = output;
};
function myFunction() {
var H1 = document.getElementById("H1");
// calling function
H1.Spacefy();
};
<h1 id="H1">
<!-- The tags inside the h1 will not be taken as text -->
<div>
Hello
</div>
</h1>
<br />
<button onclick="myFunction ()">Space-fy</button>
You can also click the button more than once :)
Note :- this script has a flow, it will not work for a nested DOM structure refer to chat to know more
Here is a link to chat if you need to discuss anything
Here is a good codepen provided by bgran which works better
I am wondering how to take the information from a parsed query string and use it to display on the top of my page. Ignore the window.alert part of the code, I was just using that to verify that the function worked.
For example: If the user had choices of Spring, Summer, Winter, and Fall, whichever they chose would display a a header on the next page. So if (seasonArray[i]) = Fall, I want to transfer that information into the form and display it as a element. I'm sure this is easily done, but I can't figure it out. Thanks, in advance.
function seasonDisplay() {
var seasonVariable = location.search;
seasonVariable = seasonVariable.substring(1, seasonVariable.length);
while (seasonVariable.indexOf("+") != -1) {
seasonVariable = seasonVariable.replace("+", " ");
}
seasonVariable = unescape(seasonVariable);
var seasonArray = seasonVariable.split("&");
for (var i = 0; i < seasonArray.length; ++i) {
window.alert(seasonArray[i]);
}
if (window != top)
top.location.href = location.href
}
<h1 id="DynamicHeader"></h1>
Replace the alert line with:
document.getElementById("DynamicHeader").insertAdjacentHTML('beforeend',seasonArray[i]);
I apologize in advance, this is the first Stack Overflow question I've posted. I was tasked with creating a new ADA compliant website for my school district's technology helpdesk. I started with minimal knowledge of HTML and have been teaching myself through w3cschools. So here's my ordeal:
I need to create a page for all of our pdf and html guides. I'm trying to create a somewhat interactable menu that is very simple and will populate a link array from an onclick event, but the title="" text attribute drops everything after the first space and I've unsuccessfully tried using a replace() method since it's coming from an array and not static text.
I know I'm probably supposed to use an example, but my work day is coming to a close soon and I wanted to get this posted so I just copied a bit of my actual code.
So here's what's happening, in example 1 of var gmaildocAlt the tooltip will drop everything after Google, but will show the entire string properly with example 2. I was hoping to create a form input for the other helpdesk personnel to add links without knowing how to code, but was unable to resolve the issue of example 1 with a
var fix = gmaildocAlt.replace(/ /g, "&nb sp;")
//minus the space
//this also happens to break the entire function if I set it below the rest of the other variables
I'm sure there are a vast number of things I'm doing wrong, but I would really appreciate the smallest tip to make my tooltip display properly without requiring a replace method.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (i = 0; i < gmailvidTitle.length; i++) {
arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>
Building HTML manually with strings can cause issues like this. It's better to build them one step at a time, and let the framework handle quoting and special characters - if you're using jQuery, it could be:
var $link = jQuery("<a></a>")
.attr("href", gmaildocLink[i])
.attr("title", gmaildocAlt[i])
.html(gmaildocTitle[i]);
jQuery("#gmailList").append($link).append("<br>");
Without jQuery, something like:
var link = document.createElement("a");
link.setAttribute("href", gmaildocLink[i]);
link.setAttribute("title", gmaildocAlt[i]);
link.innerHTML = gmaildocTitle[i];
document.getElementById("gmailList").innerHTML += link.outerHTML + "<br>";
If it matters to your audience, setAttribute doesn't work in IE7, and you have to access the attributes as properties of the element: link.href = "something";.
If you add ' to either side of the variable strings then it will ensure that the whole value is read as a single string. Initially, it was assuming that the space was exiting the Title attribute.
Hope the below helps!
UPDATE: If you're worried about using apostrophes in the title strings, you can use " by escaping them using a . This forces JS to read it as a character and not as part of the code structure. See the example below.
Thanks for pointing this one out guys! Sloppy code on my part.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google's Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
var arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (var i = 0; i < gmailvidTitle.length; i++) {
var arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>