Replace one string within array - javascript

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!

Related

JavaScript get url segment and parameter

I've read some question but I still can't figure out how to do it
I have a url example.com/event/14aD9Uxp?p=10
Here I want to get the 14aD9Uxp and the value of p
I've tried using split('/'+'?p=') but it doesn't work
I want to use regex but I dont really understand how to use it
var URL='example.com/event/14aD9Uxp?p=10';
var arr=URL.split('/');//arr[0]='example.com'
//arr[1]='event'
//arr[2]='14aD9Uxp?p=10'
var parameter=arr[arr.length-1].split('?');//parameter[0]='14aD9Uxp'
//parameter[1]='p=10'
var p_value=parameter[1].split('=')[1];//p_value='10';
I've created a generalized function (restricted in some ways) that will return the GET value given the parameter. However this function will only work correctly provided that you do not Rewrite the URL or modify the URL GET SYNTAX.
//Suppose this is your URL "example.com/event/14aD9Uxp?p=10";
function GET(variable) {
var str = window.location.href;
str = str.split("/");
// str = [example.com, event, 14aD9Uxp?p=10]
//Get last item from array because this is usually where the GET parameter is located, then split with "?"
str = str[str.length - 1].split("?");
// str[str.length - 1] = "14aD9Uxp?p=10"
// str[str.length - 1].split("?") = [14aD9Uxp, p=10]
// If there is more than 1 GET parameter, they usually connected with Ampersand symbol (&). Assuming there is more, we need to split this into another array
str = str[1].split("&");
// Suppose this is your URL: example.com/event/14aD9Uxp?p=10&q=112&r=119
// str = [p=10, q=112, r=119]
// If there is only 1 GET parameter, this split() function will not "split" anything
//Remember, there might only be 1 GET Parameter, so lets check length of the array to be sure.
if (str.length > 1) {
// This is the case where there is more than 1 parameter, so we loop over the array and filter out the variable requested
for (var i = 0; i < str.length; i++) {
// For each "p=10" etc. split the equal sign
var param_full_str = str[i].split("=");
// param_full_str = [p, 10]
//Check if the first item in the array (your GET parameter) is equal to the parameter requested
if (param_full_str[0] == variable) {
// If it is equal, return the second item in the array, your GET parameter VALUE
return param_full_str[1];
}
}
} else {
// This is the case where there is ONLY 1 GET parameter. First convert it to a String Type because Javascript decided that str was no longer a String
// Now split it with the equal sign.
str = str.toString().split("=");
return str[1];
}
}
document.write(GET("p"));
function $_GET(param) {
var vars = {};
window.location.href.replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if ( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}
I have collected this from here:
http://www.creativejuiz.fr/blog/javascript/recuperer-parametres-get-url-javascript
It works great.
To use it just grab your parameter like:
var id = $_GET('id');
const url = new URL('http://example.com/event/14aD9Uxp?p=10');
const [,, eventId ] = url.pathname.split('/');
const p = url.searchParams.get('p');
Browser support:
https://caniuse.com/#feat=url
https://caniuse.com/#feat=urlsearchparams
Simple no-regex way
var s = "example.com/event/14aD9Uxp?p=10";
var splitByForwardSlash = s.split('/');
// To get 14aD9Uxp
splitByForwardSlash[splitByForwardSlash.length-1]
// To get p=10
splitByForwardSlash[splitByForwardSlash.length-1].split('?')[1]
I think you know how to go from here :-)

Removing two words from text from string javascript

Hey I'm looking at removing words from a string, thing is the word to replace could be two different words.
e.g.
foo = "stringtest";
id = foo.replace('string', '');
or
foo = "paragraphtest";
id = foo.replace('paragraph', '');
at the moment I've approached the problem as so.
foo = "paragraphtest";
id = foo.replace('paragraph', '');
id = foo.replace('string', '');
I know this code could easily be improve but I don't know how :( thanks for your assistance.
Like this?
var foo = ["paragraph","string"];
var id = foo.replace(new RegExp(foo.join("|"),""));
The above creates array with strings you want to replace and joins it with | in RegExp constructor and replaces the match with empty string.
if(foo.indexOf("ph") > -1)
id = foo.replace('paragraph', '');
else
id = foo.replace('string', '');
Something like this maybe. Which will also give you the flexibility to modify what you replace each string with.
var replacementCharacters = [
{
searchString: "paragraph",
replacementString: ""
},
{
searchString: "string",
replacementString: ""
}
];
function runReplacement(str) {
var returnValue = str;
for (var i = 0; i < replacementCharacters.length; i++) {
returnValue = returnValue.replace(replacementCharacters[i].searchString, replacementCharacters[i].replacementString);
}
return returnValue;
}
var foo = "paragraphtest";
var id = runReplacement(foo);
Here is a demo http://jsfiddle.net/RfKt4/

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

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

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);

jquery split() issue

Hopefully this is easy for someone.
I have a set of checkboxes with values 1,2,3 etc with the same name attribute (cp_bundle).
I use the following code to get a comma-delimited list of those checkboxes.
var hl_calling_plan_bundle = $('input[name="cp_bundle"]:checked').getCheckboxVal() || "";
jQuery.fn.getCheckboxVal = function(){
var vals = [];
var i = 0;
this.each(function(){
vals[i++] = jQuery(this).val();
});
return vals;
}
if I check the first and third checkboxes, the following will be returned:
1,3
Then, I want to run a test to see whether a particular value (e.g. "3") exists in the the returned variable
But, I can't get past the split of the variable using the following:
var aCallingBundle = hl_calling_plan_bundle.split(",");
This gives the error:
hl_calling_plan_bundle.split is not a function
Any idea what's going on?
hl_calling_plan_bundle is an array. You have to use array operations on it, not string operations.
If you want to know if the value 3 is in the array, then you have to search the array for it. There are many ways to search an array, but since you have jQuery, it's easy to use the .inArray() function:
var index = $.inArray(3, hl_calling_plan_bundle);
if (index != 1) {
// found 3 in the array at index
}
Incidentally, you may want to simplify your function like this:
jQuery.fn.getCheckboxVal = function(){
var vals = [];
this.each(function(){
vals.push(this.value);
});
return vals;
}
or this way:
jQuery.fn.getCheckboxVal = function(){
return(this.map(function(){return(this.value)}).get());
}
split() is a String method, it does not exist on an Array.
When you say the following is returned 1,3, you may be implicitly calling the String's toString() method, which will by default join() the array members with a comma. If you explicitly called toString(), then you could call split(), but that would be an anti pattern.
You don't need to split the string, you can just use RegEx to search:
var str = '1,3,22,5';
/\b1\b/.test(str); // true
/\b2\b/.test(str); // false
/\b3\b/.test(str); // true
/\b5\b/.test(str); // true
/\b22\b/.test(str); // true
Making it a function:
String.prototype.findVal = function(val){
var re = new RegExp('\\b' + val + '\\b');
re.lastIndex = 0;
return re.test(this);
};
str.findVal(2); // false
str.findVal(22); // true
To get the checkboxes:
var cbs = document.getElementsByName('cp_bundle');
To get arrays of all values and the checked values:
var allValues = [];
var checkedValues = [];
for (var i=0, iLen=cbs.length; i<iLen; i++) {
if (cbs[i].checked) checkedValues.push(cbs[i].value);
allValues[i] = cbs[i].value;
}

Categories