Find matched letter from each word in javascript array - javascript

I have an array in javascript like that :
var books = ['spring','last night','sweet heart','the sky','tomorrow'] ;
I have textarea
<textarea id="text" name="textpreview" class="text"></textarea>
So what I want is when I enter letter s then I will get two suggestions books just the first word not the second word I mean not sky Just spring and sweet heart .
I will get two spans
<textarea id="text" name="textpreview" class="text"></textarea>
<span>spring</span>
<span>sweet heart</span>
If I type again after s the p letter like sp in textarea then I will get just spring
<textarea id="text" name="textpreview" class="text"></textarea>
<span>spring</span>
and so on .
If I type n I will get nothing.
If I type t I will get tomorrow and the sky
Hope it can be done . Thanks for your support .

This help you :
<html>
<head>
<title></title>
</head>
<body>
<textarea id="text" name="textpreview" class="text"></textarea>
<p id="x"></p>
<script>
var x = document.getElementById("x");
var books = ['spring','last night','sweet heart','last night','the sky','tomorrow','tomorrow'];
var txt = document.getElementById("text");
txt.onkeyup = function(event) {
var str = "";
var arr = [];
var index = (txt.value).indexOf("#");
if(index !== -1 && (txt.value).substr(index + 1).length > 0) {
var value = (txt.value).substr(index + 1);
value = value.replace(/[\.\+\*\\\?]/g,'\\$&');
var patt = new RegExp("^" + value);
for(var i=0; i<books.length; i++) {
if(patt.test(books[i]) && arr.indexOf(books[i]) === -1) {
arr.push(books[i]);
}
}
}
if (arr.length < 1 )
x.innerHTML = "";
else {
for(var i=0; i<arr.length; i++)
str+=arr[i]+"<br>";
x.innerHTML = str;
}
}
</script>
</body>
</html>

This problem consists of two parts: Reading and writing your input/output from/to the DOM, and filtering your array books.
The reading and writing part should be easy, there are plenty of guides on how to achieve this.
To filter the books array, JavaScript offers a number of helpful functions:
var books = ['spring','last night','sweet heart','the sky','tomorrow'];
var input = 'S';
var result = books.filter(function(book) {
return book.toLowerCase().indexOf(input.toLowerCase()) === 0;
}).slice(0, 2);
console.log(result); // ['spring', 'sweet heart']

#TimoSta is correct that this is a two-part problem.
I expanded on his code a bit using angular to display the results in the DOM.
http://jsfiddle.net/kcmg9cae/
HTML:
<div ng-controller="MyCtrl">
<textarea id="text" name="textpreview" class="text" ng-model="startsWith"></textarea>
<span ng-repeat="book in sortedBooks()">{{ book }}</span>
</div>
Javascript:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.books = ['spring','last night','sweet heart','the sky','tomorrow'];
$scope.sortedBooks = function () {
var sortedBooks = [];
for (var i = 0; i < $scope.books.length; i++){
if ($scope.books[i].toLowerCase().indexOf($scope.startsWith.toLowerCase()) === 0)
sortedBooks.push($scope.books[i]);
}
return sortedBooks;
}
}

Related

Find the word after specific word

i am new in javascript.
I have below code where textarea contains text as...
<textarea id="myBox" >
{Picker:} Helper
This is just demo...
</textarea>
<br/>
<span id="ans"></span> <br/>
<input type="button" onclick="getWord()" value="Click"/>
i am trying to find out the word exact after the {Picker:}, i.e. i want to find word "Helper". So word {Picker:} is the point from where i am starting to find immediate word after it. For this i using indexOf. What i did uptil now is ...
<script>
function getWord() {
var val = $("#myBox").val();
var myString = val.substr((val.indexOf("{Picker:}")) + parseInt(10), parseInt(val.indexOf(' ')) );
$("#ans").text(myString);
}
</script>
will anyone guide me to find what mistake i am making. Thanks in advance.
You should start from the index of "{Picker:}" + 9, because the length of the particular string is 9.
Parse till the the index of '\n' which is the line break character.
String.prototype.substr() is deprecated, use String.prototype.substring() instead.
function getWord() {
var val = $("#myBox").val();
var myString = val.substring((val.indexOf("{Picker:}")) + 9, val.indexOf('\n'));
$("#ans").text(myString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<textarea id="myBox">
{Picker:} Helper
This is just demo...
</textarea>
<br />
<span id="ans"></span> <br />
<input type="button" onclick="getWord()" value="Click" />
var val = $("#myBox").val();
console.log(val)
var tempArray = val.replace("\n", " ").split(" ");
var wordToFind;
for(var i = 0 ; i < tempArray.length; i++) {
var word = tempArray[i];
if (word == "{Picker:}") {
wordToFind = tempArray[i + 1]
}
}
console.log(wordToFind)
This will assign what ever word comes after Picker: to the wordToFind variable.
Check working :https://jsfiddle.net/o5qasnd0/14/
You could do something like this
const text = "{Picker:} Helper";
const wordArr = text.split(' ');
const idx = wordArr.indexOf('{Picker:}');
console.log(idx != -1 && (idx + 1) < wordArr.length ? wordArr[idx + 1] : 'not found');

Searching for actors JS

I'm making a function to find the all movies made by the actor i search for, the movies are in a js file like so:
var filmlist = [
{"Title":"Killer's Kiss", "Actors":"Frank Silvera, Jamie Smith, Irene Kane, Jerry Jarrett"}
];
var a = document.getElementById("film");
function findActors() {
var x = document.getElementById("actor").value;
var y = document.getElementById("actorfilm");
a.innerHTML = "Movies with this actor: "
for (var i=0; i<filmlist.length; i++) {
if (x.indexOf(filmlist[i].Actors) !== -1) {
y.innerHTML = (filmlist[i].Title + "<br/>")
}
}
}
<textarea rows="2" cols="50" id="actor" placeholder="write actor name, and press the button"></textarea>
<button onclick="findActor()">ActorButton</button>
<p id="film"></p>
<p id="actorfilm"></p>
For some reason it wont show the actors, but it shows the first a.innerhtml
Im very new to javascript so any help is appreciated.
You are almost there, just that your if condition needs to be reversed.
if (filmlist[i].Actors.indexOf(x) )
You were checking the superset of actors within the value you have input, rather than doing it the other way round.
You can make it more precise by doing
var filteredFilms = filmlist.filter( s => s.Actors.indexOf(x) != -1 );
var output = filteredFilms.map( s => s.Title ).join( "<br/>" );
Demo
var filmlist = [{
"Title": "Killer's Kiss",
"Actors": "Frank Silvera, Jamie Smith, Irene Kane, Jerry Jarrett"
}];
var a = document.getElementById("film");
function findActors() {
var x = document.getElementById("actor").value;
var y = document.getElementById("actorfilm");
a.innerHTML = "Movies with this actor: "
var filteredFilms = filmlist.filter(s => s.Actors.indexOf(x) != -1);
y.innerHTML = filteredFilms.map(s => s.Title).join("<br/>");
}
<!-- find actor function -->
<textarea rows="2" cols="50" id="actor" placeholder="write
actor name, and press the button">Frank Silvera</textarea>
<button onclick="findActors()">ActorButton</button>
<p id="film"></p>
<p id="actorfilm"></p>
You are currently overwriting y.innerHTML with the last movie title. To append, to the innerHTML use:
y.innerHTML += (filmlist[i].Title + "<br/>")
There is an issue with your indexOf, mentioned in another answer and can be fixed with
if (filmlist[i].Actors.indexOf(x)) {
Lastly, your HTML is incorrectly referencing the js function and should instead be:
<button onclick="findActors()">ActorButton</button>

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>

Javascript Product Search (working, but need to filter by search term)

I have a little product search code that I've been working on for a while. It works great, although a bit backwards.
The more keywords I type in, ideally, the less products will show up (because it narrows down the results). But as is stands, the more keywords I type in my search system, the MORE products are displayed, because it looks for any product with any of the keywords.
I want to change the script so that it only shows results if they include ALL the searched for keywords, not ANY of them...
Sorry for the long-winded explanation.
Here's the meat and potatoes (jsfiddle):
http://jsfiddle.net/yk0Lhneg/
HTML:
<input type="text" id="edit_search" onkeyup="find_my_div();">
<input type="button" onClick="find_my_div();" value="Find">
<div id="product_0" class="name" style="display:none">Mac
<br/>Apple
<br/>
<br/>
</div>
<div id="product_1" class="name" style="display:none">PC
<br/>Windows
<br/>
<br/>
</div>
<div id="product_2" class="name" style="display:none">Hybrid
<br/>Mac PC Apple Windows
<br/>
<br/>
</div>
JAVASCRIPT:
function gid(a_id) {
return document.getElementById(a_id);
}
function close_all() {
for (i = 0; i < 999; i++) {
var o = gid("product_" + i);
if (o) {
o.style.display = "none";
}
}
}
function find_my_div() {
close_all();
var o_edit = gid("edit_search");
var str_needle = edit_search.value;
str_needle = str_needle.toUpperCase();
var searchStrings = str_needle.split(/\W/);
for (var i = 0, len = searchStrings.length; i < len; i++) {
var currentSearch = searchStrings[i].toUpperCase();
if (currentSearch !== "") {
nameDivs = document.getElementsByClassName("name");
for (var j = 0, divsLen = nameDivs.length; j < divsLen; j++) {
if (nameDivs[j].textContent.toUpperCase().indexOf(currentSearch) !== -1) {
nameDivs[j].style.display = "block";
}
}
}
}
}
So, when you search "mac pc" the only result that should be displayed is the hybrid, because it has both of those keywords. Not all 3 products.
Thank you in advance!
I changed a little bit your code to adjust it better to my solution. I hope you don't mind. You loop first over the terms, and then through the list of products, I do it the other way around.
How this solution works:
Traverse the list of products, for each product:
Create a counter and set it to 0.
Traverse the list of search terms, for each.
If the word is found in the product's name, add 1 to the counter.
If the counter has the same value as the list length, display the product (matched all words)
function gid(a_id) {
return document.getElementById(a_id);
}
function close_all() {
for (i = 0; i < 999; i++) {
var o = gid("product_" + i);
if (o) {
o.style.display = "none";
}
}
}
function find_my_div() {
close_all();
var o_edit = gid("edit_search");
var str_needle = edit_search.value;
str_needle = str_needle.toUpperCase();
var searchStrings = str_needle.split(/\W/);
// I moved this loop outside
var nameDivs = document.getElementsByClassName("name");
for (var j = 0, divsLen = nameDivs.length; j < divsLen; j++) {
// set a counter to zero
var num = 0;
// I moved this loop inside
for (var i = 0, len = searchStrings.length; i < len; i++) {
var currentSearch = searchStrings[i].toUpperCase();
// only run the search if the text input is not empty (to avoid a blank)
if (str_needle !== "") {
// if the term is found, add 1 to the counter
if (nameDivs[j].textContent.toUpperCase().indexOf(currentSearch) !== -1) {
num++;
}
// display only if all the terms where found
if (num == searchStrings.length) {
nameDivs[j].style.display = "block";
}
}
}
}
}
<input type="text" id="edit_search" onkeyup="find_my_div();">
<input type="button" onClick="find_my_div();" value="Find">
<div id="product_0" class="name" style="display:none">Mac
<br/>Apple
<br/>
<br/>
</div>
<div id="product_1" class="name" style="display:none">PC
<br/>Windows
<br/>
<br/>
</div>
<div id="product_2" class="name" style="display:none">Hybrid
<br/>Mac PC Apple Windows
<br/>
<br/>
</div>
You can also see it on this version of your JSFiddle: http://jsfiddle.net/yk0Lhneg/1/

Limiting character in textbox input

please be nice. I'm trying to create a page which sets limit and cut the excess (from the specified limit). Example: Limit is 3. then, I'll input abc if I input d it must say that its limit is reached and the abc will remain. My problem is that it just delete my previous input and make new inputs. Hoping for your great cooperation. Thanks.
<html>
<script type="text/javascript">
function disable_btn_limit(btn_name)
{
/* this function is used to disable and enable buttons and textbox*/
if(btn_name == "btn_limit")
{
document.getElementById("btn_limit").disabled = true;
document.getElementById("ctr_limit_txt").disabled = true;
document.getElementById("btn_edit_limit").disabled = false;
}
if(btn_name == "btn_edit_limit")
{
document.getElementById("btn_limit").disabled = false;
document.getElementById("ctr_limit_txt").disabled = false;
document.getElementById("btn_edit_limit").disabled = true;
}
}
function check_content(txtarea_content)
{
/*This function is used to check the content*/
// initialize an array
var txtArr = new Array();
//array assignment
//.split(delimiter) function of JS is used to separate
//values according to groups; delimiter can be ;,| and etc
txtArr = txtarea_content.split("");
var newcontent = "";
var momo = new Array();
var trimmedcontent = "";
var re = 0;
var etoits;
var etoits2;
//for..in is a looping statement for Arrays in JS. This is similar to foreach in C#
//Syntax: for(index in arr_containter) {}
for(ind_val in txtArr)
{
var bool_check = check_if_Number(txtArr[ind_val])
if(bool_check == true)
{
//DO NOTHING
}
else
{
//trim_content(newcontent);
newcontent += txtArr[ind_val];
momo[ind_val] = txtArr[ind_val];
}
}
var isapa = new Array();
var s;
re = trim_content(newcontent);
for(var x = 0; x < re - 1; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
}
function trim_content(ContentVal)
{
//This function is used to determine length of content
//parseInt(value) is used to change String values to Integer data types.
//Please note that all value coming from diplay are all in String data Type
var limit_char =parseInt(document.getElementById("ctr_limit_txt").value);
var eto;
if(ContentVal.length > (limit_char-1))
{
alert("Length is greater than the value specified above: " +limit_char);
eto = limit_char ;
etoits = document.getElementById("txtarea_content").value;
//document.getElementById("txtarea_content").value = "etoits";
return eto;
//for(var me = 0; me < limit_char; me++)
//{document.getElementById("txtarea_content").value = "";}
}
return 0;
}
function check_if_Number(ContentVal)
{
//This function is used to check if a value is a number or not
//isNaN, case sensitive, JS function used to determine if the values are
//numbers or not. TRUE = not a number, FALSE = number
if(isNaN(ContentVal))
{
return false;
}
else
{ alert("Input characters only!");
return true;
}
}
</script>
<table>
<tr>
<td>
<input type="text" name="ctr_limit_txt" id="ctr_limit_txt"/>
</td>
<td>
<input type="button" name="btn_limit" id="btn_limit" value="Set Limit" onClick="javascript:disable_btn_limit('btn_limit');"/>
</td>
<td>
<input type="button" name="btn_edit_limit" id="btn_edit_limit" value="Edit Limit" disabled="true" onClick="javascript:disable_btn_limit('btn_edit_limit');"/>
</td>
</tr>
<tr>
<td colspan="2">
<textarea name="txtarea_content" id="txtarea_content" onKeyPress="javascript:check_content(this.value);"></textarea>
<br>
*Please note that you cannot include <br>numbers inside the text area
</td>
</tr>
</html>
Try this. If the condition is satisfied return true, otherwise return false.
<html>
<head>
<script type="text/javascript">
function check_content(){
var text = document.getElementById("txtarea_content").value;
if(text.length >= 3){
alert('Length should not be greater than 3');
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<div>
<textarea name="txtarea_content" id="txtarea_content" onkeypress=" return check_content();"></textarea>
</div>
</body>
</html>
Instead of removing the extra character from the text area, you can prevent the character from being written in the first place
function check_content(event) { //PARAMETER is the event NOT the content
txtarea_content = document.getElementById("txtarea_content").value; //Get the content
[...]
re = trim_content(newcontent);
if (re > 0) {
event.preventDefault(); // in case the content exceeds the limit, prevent defaultaction ie write the extra character
}
/*for (var x = 0; x < re - 1; x++) {
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}*/
}
And in the HTML (parameter is the event):
<textarea ... onKeyPress="javascript:check_content(event);"></textarea>
Try replacing with this:
for(var x = 0; x < re - 6; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
Any reason why the maxlength attribute on a text input wouldn't work for so few characters? In your case, you would have:
<input type="text" maxlength="3" />
or if HTML5, you could still use a textarea:
<textarea maxlength="3"> ...
And then just have a label that indicates a three-character limit on any input.

Categories