find exact value from user input to csv file content - javascript

I have a simple HTML file with input text id="ERP", I want the user to be able to find the exact match to the CSV file content. Here is the code I have been trying to fix. This searches the CSV file but returns result not exactly as the value entered from input box, Example, input box value = "CH-134", the out-put will show data for "CH-134-DT" how can I make the search result exactly the same as the input? Thank you in advance.
var DB = new Array();
function MakeDB() { DB = CSV.split('\n'); }
function CSVsearch(dbInfo) {
var posn = -1;
for (i=0; i<DB.length; i++) {
tmp = DB[i];
if (tmp.indexOf(dbInfo) != -1) { posn = i; break; }
}
if (posn == -1) { alert('No matching result from the file'); }
else { document.getElementById('tblDisplay').innerHTML = displayAsTable(DB[posn]); }
}
function displayAsTable(info) {
var table = '<table border="1" width="75%" bgColor="F5F5F5" borderColor="FFFFFF">';
var ary = info.split(',');
table += '<tr align="left"><th align="left">'+ary.join('</tr><th align="left">')+'</td></tr>';
table += '</table>';
return table;
}
function resetthis() {
document.getElementById("myForm").reset();
}

I think I would use the Javascript str.match(regexp) function and a regular expression, instead of using the str.indexOf(searchValue) function.
So in your case, I'd do something like:
var regex = '/\b' + dbInfo + '\b/g';
var matches = tmp.match(regex);
if (matches.length > 0)
{ ... }
Just replace the '\b' above with whatever you'd expect your incoming data to be separated by. For example, if you expect to find CH-134 is in your dataset with spaces before and after, you can leave the '\b' there. If it is in your dataset with commas, you can replace '\b' with ','. Or if you only know what terminates the word you're trying to match, you can leave off the first '\b' from the regex. For example, you could do something like:
//finds occurences of dbInfo with anything before it, but only a comma after it
var regex = '/' + dbInfo + ',/g';
//finds occurences of dbInfo with a word break before it, and no hyphen after it
var regex = '/\b' + dbInfo + '[^-]/g';
You'll probably be able to come up with a better, more precise, regular expression for your needs. My favorite site for playing with and testing out regular expressions is http://regexr.com/
Good luck!

tadaaa, as according to Seth, I added the dbInfo + ',' and simply put the 'while' so the loop wont stop when the search hits a similar value. WoohOooo
var DB = new Array();
function MakeDB() { DB = CSV.split('\n'); }
function CSVsearch(dbInfo) {
var posn = -1;
var input = document.getElementById('ERP').value;
for (i=0; i<DB.length; i++) {
tmp = DB[i]; //ROW DATA
while (tmp.indexOf(dbInfo+',') != -1) { posn = i; break; }
}
var data = DB[posn];
if (posn >=0) { (alert('RECORD FOUND!\nERP: ' + dbInfo));
document.getElementById('tblDisplay').innerHTML = displayAsTable(data); }
else { (alert ('NO RECORD FOUND')); }
}
function displayAsTable(info) {
var table = '<table border="1" width="75%" bgColor="F5F5F5" borderColor="FFFFFF">';
var ary = info.split(',');
table += '<tr align="left"><th align="left">'+ary.join('</tr><th align="left">')+'</td></tr>';
table += '</table>';
return table;
}
function resetthis() {
document.getElementById("myForm").reset();
}

Related

Replacing hashtag with links, it only replaces last word in the string

I am trying to make a hashtag system, so I reached the edit text feature where I want to replace the entered edit with hashtag links if the user type hashtag words. So I am using JavaScript and jQuery to do this but the problem is that the for loop is only replacing the last word in the string and not all the string with a links.
// Turn hashtags into links
var discussionText = "#example #text #string #one #two #three #hashtag #word";
var wordsArray = discussionText.split(" ");
for (i = 0; i < wordsArray.length; i++) {
console.log(i);
if (wordsArray[i].indexOf('#') > -1) {
var wordWithoutHashtag = wordsArray[i].replace("#", "");
console.log(wordWithoutHashtag);
$("#" + editDiscussionButtonId + "-" + editDiscussionButtonUserId + "-spanDiscussionEdit").html(function() {
return $(this).text().replace(wordsArray[i], "<a href='search.php?sec=all&q=" + wordWithoutHashtag + "' class='hashtag_link'>" + wordsArray[i] + "</a>");
});
}
}
Change the html(function) to use the existing html argument. When you use text() it doesn't return the previous <a> you created in previous iterations of the loop, only the text inside the <a>.
$(selector).html(function(index, existingHtml){
return existingHtml.replace(wordsArray[i], ....
});
Similarly if you just changed $(this).text().replace.. to $(this).html().replace... it would work.
A more efficient approach would be the get the existing content once before the loop and do all the modifications to the string stored in variable, then replace the modified content once after the loop completes
After i posted this question, i continue trying with solutions until i came up with the below which works perfectly for all cases tags
var discussionText = "#example #text #string #one #two #three #hashtag #word";
var wordsArray = discussionText.split(" ");
var fullText = "";
for(i=0; i < wordsArray.length; i++) {
if (wordsArray[i].indexOf('#') > -1) {
var wordWithoutHashtag = wordsArray[i].replace("#", "");
var wordLink = wordsArray[i].replace(wordsArray[i], "<a href='search.php?sec=all&q="+wordWithoutHashtag+"' class='hashtag_link'>"+wordsArray[i]+"</a>");
fullText += " " + wordLink;
$("#"+editDiscussionButtonId+"-"+editDiscussionButtonUserId+"-spanDiscussionEdit").html(fullText);
} else {
fullText += " "+wordsArray[i];
}
}

How to manipulate the characters written in a div to work with them afterwards using javascript

function doGetWord(){
var word = F.gword.value;
var wLength = word.length;
for(var i = 0; i < wLength; i++){
document.getElementById("dword").innerHTML += "_ "
}
}
This is a function that will write _ in a div in html, and what I want is to change them if the user types the corresponding input, for example if the first letter is supposed to be "a" then it would change the first _ to "a".
This is what I got so far:
function doGuessWord(){
dummy = F.t.value
if(dummy.length > 1){
dummy = ""
F.t.value = ""
}
for(var x = 0; x < wLength; x++){
if (substr(x, wLength) == dummy ) {
document.getElementById("dword").innerHTML += "_ "
}
else{
document.getElementById("dword").innerHTML += "dummy "
}
}
}
Could you help me out with this one?
Thanks in Advance!!
Something like this?
https://jsfiddle.net/9z66968a/3/
You will have to adapt it a bit. But you should be able to take the parseText function and pass it the params you need to return the text to insert where ever you want
There you go. I believe this is what you wanted. Feel free if you don't understand something
https://jsfiddle.net/vhsf8gpp/2/
var dashArr = [];
var dummyWord = document.getElementById('dummy');
var input = document.querySelector('input');
var counter = 0;
for(let i= 0; i<10;i++)
{
dashArr.push('_');
}
function WriteContent()
{
dummyWord.textContent = dashArr.map(d=>d).join(''); // This gets rid of the ',' inbetween the dashes
}
WriteContent();
//var charArr = [];
document.querySelector('input').addEventListener('keyup',function(){
var inputString = input.value;
dashArr[counter] = inputString.charAt(inputString.length - 1);
WriteContent();
counter++;
})
I used this post for reference.

Check whether a word is in a text box regardless of case

I am trying to figure out whether a text box has a given word, regardless of case. For example, how can I determine whether a given text box, #TextBox, has the word "hello" in it?
var specialwords = ['hello','Hello','HELLO']; //special words here
$('#TextBox').keydown(function() {
var text = $(this).val();
text = text.split(" ");
var newtext = "";
for(var i = 0; i < text.length; i++){
// code to check words
}
$("#check").html(newtext);
});
The easiest way to check whether a text box has a given word, irrespective of case, is to convert the text box to lowercase, then split by spaces and find the indexOf the word.
var word = "hello".toLowerCase(); // make sure this word is lowercase
$("#TextBox").keydown(function () {
var text = $(this).val().toLowerCase().split(" ");
if (text.indexOf(word) > -1) {
// do something
} else {
// word is not in the text box
}
})
If you want to check for an array of words, specialWords, wrap the if block in a for loop. This would be O(n²) complexity, but that should be fine, as long as your input isn't extremely long1.
1we're talking thousands upon thousands of words long for it to matter.
function checkAlphaCase(alpha) {
if (alpha == alpha.toLowerCase()) {
alert('LowerCase');
} else if (alpha == alpha.toUpperCase()) {
alert('UppperCase');
} else {
alert('MixedCase');
}
}
checkAlphaCase('ANIR');
TRY this
$(document).ready(function(){
var specialwords = ['hello','Hello','HELLO'];//special words here
$('#TextBox').keydown(function() {
//alert(this);
var text = $(this).val().trim();
console.log(text);
// text = text.trim().split(" ");
var newtext = "";
var up=0,low=0;
for(var i=0;i<text.length;i++){
if(text[i]==" ")
continue;
else{
if(text[i].trim()==text[i].trim().toLowerCase())
low++;
if(text[i].trim()==text[i].trim().toUpperCase())
up++;
}
}
if(up>0 && low>0)
newtext="mix case";
else if(up>0)
newtext="Upper case";
else if(low>0)
newtext="Lower case"
$("#check").html(newtext);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="TextBox">
<div id="check"></div>
You can make a case insensitive regex with all the words like this:
RegExp("\\b(?:" + specialwords.join("|") + ")\\b", "i")
then you can use it against each word. I am not sure what you are doing with the words once you identify them ... I will assume for the purpose of my code snippet that you are ignoring them from the text.
var specialwords = ['hello','world','pizza']; //special words here
var swr = RegExp("\\b(?:" + specialwords.join("|") + ")\\b", "i")
$('#TextBox').keydown(function() {
var text = $(this).val();
text = text.split(" ");
var newtext = [];
for(var i=0; i<text.length; i++){
if (!text.match(swr)) {
newtext.push(text)
}
}
$("#check").html(newtext.join(" "));
});
Using the \b as a word delimiter in regexp you can also check the whole text without breaking up the words if you want.
var specialwords = ['hello','world','pizza']; //special words here
var swr = RegExp("\\b(?:" + specialwords.join("|") + ")\\b", "i")
$('#TextBox').keydown(function() {
var text = $(this).val();
var newtext = text.replace(swr, "");
$("#check").html(newtext);
});

Remove extra white spaces from Array

The elements in my list should be
A1,A2,A3,A4
If user input A1,A2,A3,A4,,,,,,
or
A1,A2,,,A3,A4,,A5,,
or
A,B, ,, ,, V,,,, , , , , ,ddfd ,,,,,,,,
It should consider as
A1,A2,A3,A4
The logic written by me was
if(valueText !== null) { alert("Value Text..." + valueText);
valueList = valueText.split(",");
for (var i = 0; i < valueList.length; i++)
{
if (valueList[i] == "")
{
valueList.splice(i, 1);
alert("ValueList inside for if.."+valueList);
}
}
alert("ValueList.." + valueList);
}
But its not working properly
You can do something like this with match & join functions:-
var str = "A1,A2,,,A3,A4,,A5,,";
strnew = str.match(/[^ ,]+/g).join(',');
//Output--> A1,A2,A3,A4,A5
Hope this will help you...
You can do this with regex, for example:
var txt = 'A1,A2,,,A3,A4,,A5,,'
var res = txt.replace(/(,)\1*/g, ',').replace(/,$/, '');
//^ A1,A2,A3,A4,A5

jQuery Loop through text content while keeping wrapping html tags

I have the following javascript function that aims to append a BIDI code to text that matches a specific criteria.The problem with the current function is that it works great with text only content but is problematic with content that has HTML Content. To summarize, I am splitting the text into words and checking if any of the characters in each word is matching a certain criteria to append the BIDI code to it.
The current status:
<div>This is the text that I am processing</div> //This works great
<div><span>This is the text</span><p>that I am processing</p></div> // This doesn't work well.
I want the function to work is for the text but also to keep the wrapping HTML tags in their place in order to keep etc....
function flipper(flipselector) {
var pagetitle = $(flipselector);
var text = pagetitle.text().split(' '); //I know that I am using text function here but .html didn't work either
var newtext="";
for( var i = 1, len = text.length; i < len; i=i+1 ) {
//text[i] = '<span>' + text[i] + '</span>';
newstring="";
if (matches = text[i].match(/\d/))
{
var currentstring=text[i];
for (var x = 0, charlen = currentstring.length; x < charlen; x++) {
if (matches = currentstring[x].match(/\d/)) {
varnewchar=currentstring[x];
}else {
varnewchar= "‏" + currentstring[x];
}
newstring=newstring + varnewchar;
}
} else {
newstring= text[i];
}
newtext=newtext + " " + newstring;
}
pagetitle.html(newtext);
}

Categories