Remove text bricks that are defined in an array from input value - javascript

I want to edit the value of an input field! To detail i want to delete the text that that is defined an an array from the input:
So if i have for example:
<input value="hello what is your">
and this array:
var arr = ["hello","is"];
I want to change the value of the input to:
<input value="what your">
How should i start? Thanks http://jsfiddle.net/rRXAG/

How should i start?
1) Iteration - Since you already use jQuery, try with $.each.
2) string.indexOf() - returns -1 if it is not present
var arr = ["hello","is"];
$.each(arr, function (i, j) {
var inTxt = $('input').val();
if (inTxt.indexOf(j) != -1) {
$('input').val(inTxt.replace(j, ''));
}
});});
JSFiddle

var val=document.getElementById("yourid").value;
for(var i=0;i<arr.length;i++){
val.replace(arr[i],"")
}
document.getElementById("yourid").value=val;

This regexp do the job :
$('input').first().val().replace(new RegExp(arr.join('|'), 'g'), '');
Fiddle : http://jsfiddle.net/rRXAG/2/

Assuming the values are words separated by spaces, you can do this:
1) Store the values into a map
var map = {};
for (var i in arr) map[arr[i]] = true;
2) Get the value from your input (it's a string) and filter it
var inputVal = $('input').first().val();
var newValue = inputVal.split(" ").filter(function(x) {
return !map[x];
}).join(" ");
// Set new value
$('input').first().val(newValue);

Related

Remove duplicates in array separated by double commas in JavaScript

I have an array in JavaScript like this
var data = [,A_1_VII,VII,V2,,A_1_VII,VII,V2,,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]
when I alert in JavaScript it gives as below
,A_1_VII,VII,V2
,A_1_VII,VII,V2
,A_1_VII,VII,V2
,B_1_XIV,XIV,V3
,B_2_XVI,XVI,V3
But I want like this which is duplicates removed array
var unique_data = [,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]
On alert it should give like this
,A_1_VII,VII,V2
,B_1_XIV,XIV,V3
,B_2_XVI,XVI,V3
First Thing your array contains string as a constant that's not going to work.
Secondly, if all of you value are strings you can do it as follows:
var data =[,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV","XIV","V3",,"B_2_XVI","XVI","V3"];
var uniqueArray = data.filter(function(item, pos) {
return data.indexOf(item) == pos;
})
alert(uniqueArray);
Assuming the variables in your array are well defined, you can clean it up and remove duplicates with a for loop:
var data [/* ... */];
var unique_data = [];
for(let i = 0; i < data.length; i++) {
if (data[i] && unique_data.indexOf(data[i]) === -1) {
unique_data.push(data[i]);
}
}
Please note that the code above assumes that your array contains non-object types, otherwise the solution would need to use something more sophisticated than indexOf().
You can create your unique function to remove duplicate entry and empty value from array like this.
var data =[,"A_1_VII,VII","V2,,A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV,XIV","V3",,"B_2_XVI,XVI,V3"]
var unique_data = uniqueList(data);
alert(unique_data);
function uniqueList(list) {
var uniqueResult = [];
$.each(list, function(i, e) {
if ($.inArray(e, uniqueResult) == -1 &&$.inArray(e, uniqueResult)!="")// chech for unique value and empty value
uniqueResult.push(e);
});
return uniqueResult ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Remove strings if found remove a part of the string in JS

I'm facing a problem.
I have this:
<input type="hidden" name="Boss" id="Boss" value="8,116,167,198,139,203,158,170,">
Actually I have this code in js:
// On click on element with class .Boss
$("form").on("click", ".Boss", function(event){
var clickedId = $(this).attr('value')+','; // give me 8,
var locationBtn = $('#Boss'); // Select the input
var locationBtnValue = $('#Boss').val(); // Take the select value
if(locationBtnValue.toString().indexOf(clickedId) == -1) { locationBtn.val(locationBtnValue + clickedId); }
else { locationBtn.val(locationBtnValue.replace(clickedId,'')); }
});
My problem is: if want to decide to remove the 8 my javascript do not remove the item 8, but the first occurrence it will find in my string, so 8,116,167,19**8,**139,203,158,170,. So it breaks my other item...
How can I make to do not break it ?
Thanks.
I do not know what your final outcome is, but I think you want it to be 116,167,198,139,203,158,170, In this case you can split and filter the array to get rid of the value.
var str = "8,116,167,198,139,203,158,170,"; //the input
var updated = str.split(",") //turn it into an array
.filter(function (val) { //loop through all the elements applying this function
return val!=="8"; //keep the item if the index does not match the item
}
).join(","); //turn array back into a string
One way to be consistent is by splitting it into an array and then removing the occurence.
// On click on element with class .Boss
$("form").on("click", ".Boss", function(event) {
var clickedId = $(this).attr('value'); // give me 8
var locationBtn = $('#Boss'); // Select the input
var locationBtnValue = locationBtn.val(); // Take the select value
var ids = locationBtnValue.split(','); //split into an array
var index = ids.indexOf(clickedId); //index of clickedId inside ids
if(index > -1) { //found
ids = ids.splice(index, 1); //remove from ids
} else {
ids.push(clickedId); //add to ids
}
locationBtn.val(ids.join(','));
});
That's what replace does when you pass it a string, it replaces the first occurrence.
You need to pass it a regular expression with the global modifier, like this
locationBtnValue.replace(/8,/g,'')
you can do the same thing with the RegExp constructor, and create a regular expression from the string you have
var clickedId = $(this).val() + ',';
var regex = new RegExp(clickedId, "g");
locationBtnValue.replace(regex,'');

Replace one string within array

I have the following array:
etst,tset,tets,ttest,teest,tesst,testt,4est,test,dest
I want to delete the value of an input box from the array, here's what I'm trying:
var el = document.getElementById('searchInput').value; // this is "test"
var toSearchFor = eld.slice(0,10); // the array above
for(var i=0; i < toSearchFor.length; i++) {
toSearchFor[i] = toSearchFor[i].replace(/el/g, "");
}
It's simply not replacing "test" with ""
How can I do that?
You can use Array.filter (see MDN) to filter out the desired value:
var arr = 'etst,tset,tets,ttest,teest,tesst,testt,4est,test,dest'.split(',')
,val = 'test'
document.querySelector('#result')
.innerHTML = arr.filter(function (v) {return v != val});
<div id="result"></div>
A text field example in this jsFiddle
for global replacement of a string stored in a variable u need to create an instance of RegExp explicitly, like this:
var regex = new RegExp(el, "g");
then use it in replace function:
toSearchFor[i] = toSearchFor[i].replace(regex, "");
The problem with your code is in your regular expression: /el/g. This is trying to match the letters el, instead of whatever it's in the el variable. You could have done it using the RegExp construtor.
// ...
regexp = new RegExp(el); // No need to use 'g' here since you're looking for the whole word
toSearchFor[i] = toSearchFor[i].replace(regexp, "");
// ...
Here's another way of doing it:
var eld = ['etst','tset','tets','ttest','teest','tesst','testt','4est','test','dest'];
// var el = document.getElementById('searchInput').value;
var el = 'test';
console.log(eld);
var index = eld.indexOf(el);
if (index >= 0) {
eld[index] = '';
}
console.log(eld);
Here's the output:
["etst", "tset", "tets", "ttest", "teest", "tesst", "testt", "4est", "test", "dest"]
["etst", "tset", "tets", "ttest", "teest", "tesst", "testt", "4est", "", "dest"]
In this case, we're using Array.prototype.indexOf, which returns the first index at which a given element can be found in the array, so that we can access that element directly (if found).
I hope that helps!

JavaScript - Find and replace word in array

How would I find a word (in this case a placeholder, e.g _ORGAN_) in an array and replace it with an element's value?
sql = new Array();
$('#system').change(function(){
filter = " topography_index = _ORGAN_";
sql.push(filter);
});
In this case I would want to replace _ORGAN_ with $('#organ_menu').val();
Try this:
// sql array
var sql = ['organ not found', '_ORGAN_ is here'];
var val_to_replace = '_ORGAN_';
var replace_with = 'heart'; // temp value - change it with $('#organ_menu').val()
$.each(sql, function (key, val) {
// search for value and replace it
sql[key] = val.replace(val_to_replace, replace_with);
})
console.log(sql)
JSFiddle: http://jsfiddle.net/d8sZT/
You can simply do by iterating the array and then assign the value to once it find its match.
for (i = 0; i < sql.length; i++) {
if (sql[i] === "_ORGAN_") {
sql[i] = $('#organ_menu').val();
}
}
example fiddle for better understanding.
You can simply iterate over the array and use replace on each element
var organValue = $('#organ_menu').val();
for (var i = 0; i < sql.length; i++) {
sql[i] = sql[i].replace("_ORGAN_", organValue);
}
var regExp = new RegExp(organ, 'g');
$.each(sql, function(index, value) {
sql[index] = value.replace(regExp, 'test');
})
I'd try something like this, using replace:
sql = new Array();
$('#system').change(function(){
filter = " topography_index = _ORGAN_".replace("_ORGAN_", $('#organ_menu').val(), "gi");
sql.push(filter);
});
You can do this:
First find the index of the item:
var index=sql.indexOf("_ORGAN_");
Then insert your new item at that index and remove the first one:
sql.splice(index,1,newitem);
splice

jQuery .each: Do not add comma in last field

I want to get values of all fields in a variable separated by a comma. For example: 1,2,3
The following code will work fine, but it only adds the comma at end of the last value also. How can I remove that?
fields = $('.wrap').find('.text');
var data = '';
fields.each(function() {
var value = $(this).val();
if ( value != '' ) {
data += ' ' + value + ',';
}
});
alert(data);
JSFiddle:
http://jsfiddle.net/cn5Gt/
I always use arrays for these kind of things:
var fields = $('.wrap').find(".text[value!='']");
var data = [];
fields.each(function() {
data.push($(this).val());
});
alert(data.join(','));
You can push elements on array than just use join() method.
fields = $('.wrap').find('.text');
var data = [];
fields.each(function() {
var value = $(this).val();
if ( value != '' ) {
data.push(value);
}
});
alert(data.join());
Try the code below, using the i which is the loop index and test against the length of the jQuery object.
fields = $('.wrap').find('.text');
var length = fields.length;
var data = '';
fields.each(function(i) {
var value = $(this).val();
if ( value != '' ) {
if(i === length-1) { //The last one
data += ' ' + value;
} else {
data += ' ' + value + ',';
}
}
});
Updated fiddle
You could just remove the final character afterwards?
data = data.substr(0, data.length - 1);
http://jsfiddle.net/cn5Gt/3/
Simplest of all:just replace your last line with the below line
alert(data.slice(0,-1));//where data is string
http://jsfiddle.net/cn5Gt/7/
DOC MDN : slice
How about something like this:
var data = $('.wrap').find('.text')
.map(function(i,el){ return el.value || null; })
.get().join(", ");
Demo: http://jsfiddle.net/cn5Gt/11/
jQuery's .map() method will "Pass each element in the current matched set through a function, producing a new jQuery object containing the return values." You can still include your if ( value != '' ) { test in the callback function because if your function returns null or undefined then .map() will not use that particular value. (I've used || null above as a shortcut to an if/else structure.)
Call .get() (or .toArray()) on the result and you'll have an actual array, which means you can then use the Array .join() method to form a string with the values comma separated.
If you need to do other processing on each item besides just getting the value you could stick with the .each() loop and add the values to an array that you then join after the loop (like some of the other answers), or just use the string .slice() method to remove the trailing comma and space characters.
Try this:
Using the length function to determine the position of the each
var fields = $('.wrap').find('.text');
var len = fields.length;
var data = '';
fields.each(function(index, element) {
var value = $(this).val();
if ( value != '' ) {
data += ' ' + value;
if (index != len - 1) {
data += ',';
}
}
});
alert(data);

Categories