Calculating the length of an array of regular expressions - javascript

I have a function here that is meant to check an element against a given array of regular expressions. The array that I am passing contains ten different regular expressions.
var regExAlphabet = /[a-z]/;
var regExNumbers = /[0-9]/;
var regExWhile = /while/;
var regExIf = /if/;
var regExElse = /else/;
var regExTrue = /true/;
var regExFalse = /false/;
var regExInt = /int/;
var regExString = /string/;
var regExBoolean = /boolean/;
var regexList = [regExAlphabet, regExNumbers, regExTrue, regExFalse,
regExInt, regExString, regExBoolean, regExWhile, regExIf, regExElse];
function loopThroughOptions(regexList, element) {
for (var i = 0; i < regexList.length; i++)
failSafe(regexList[i], element) // failSafe is defined but not shown
}
var aString = "a";
loopThroughOptions(regexList, aString);
When I run this, I am getting an uncaught typeError: cannot read property length of undefined in my loopThroughOptions function. Why is this happening? How can I fix it?
EDIT: It looks like I will need to post the failSafe function. It is quite long. Take a stab at it.
var tokenList = []; // list of discovered tokens
var substringsArray = []; // any strings that are not tokens go here
function substringsHandler(array) {
for (var i = 0; i < substringsArray.length; i++) {
for (var y = 0; y < regexList.length; y++) {
failSafe(regexList[y], substringsArray[i])
}
}
}
function findAMatch(value) {
if (value == "a")
console.log("matched a");
}
function findACharMatch(value) {
if (value == "a")
console.log("matched a");
}
function failSafe(regEx, element) {
if (regEx.test(element) && element.length > 1) { // if the token is there
var x = regEx.exec(element); // give us more information on the element
var value = x["0"]; // keep track of the value of the token
var index = x.index; // keep track of the index
var substring = value;
console.log(index);
console.log(substring.length);
console.log(element.length);
tokenList.push({
value: substring,
indexFound: index});
console.log(tokenList[0]);
if (index > 0 && index + substring.length - 1 < element.length) { // if we found a token in the middle of a string
console.log("Found token in the middle of the string.");
substringsArray.push({ // give us the half that comes before the match
value: element.substring(0, index),
indexFound: 0
});
substringsArray.push({ // give us the rest of the string that occurs after the match
value: element.substring(index + value.length),
indexFound: index + value.length
});
substringsHandler(substringsArray);
// all successful token finds get sent to tokenList to search for a match
// if nothing is found, then everything gets translated to characters or digits
} else if (index > 0 && index + substring.length - 1 == element.length) { // if there is more string to the left only
console.log("Found token on the right of the string.");
substringsArray.push({
value: element.substring(0, index), // compare these values using find a match later
indexFound: 0
})
} else if (index == 0 && substring.length < element.length) { // if there is more string to the right only
console.log("Found token on the left of the string.");
substringsArray.push({
value: element.substring(substring.length),
indexFound: substring.length
})
} else { // the token is the only input
console.log("The token consists of the entire string.");
}
} else if (regEx.test && element.length == 1) {
var x = regEx.exec(element); // give us more information on the element
var value = x["0"]; // keep track of the value of the token
var index = x.index; // keep track of the index
var substring = value;
tokenList.push({
value: value,
index: index
})
} else {
console.log("No match for regexp " + regEx + "trying the next one...");
return;
}
console.log(tokenList);
tokenList.sort(function(a, b) {
return a.indexFound - b.indexFound;
});
console.log(tokenList);
for (var i = 0; i < tokenList.length; i++) {
if (tokenList[i].value.length > 1)
findAMatch(tokenList[i].value);
else
findACharMatch(tokenList[i].value);
}
};

Ok, so I ran all of your showed code and it has an error, according to RegExp docs
If the match fails, the exec() method returns null.
So, in your code, you always take for granted that regEx.exec(element); will return an array (it supposes that the RegExp will match at least one element), which, at least in your examples, is false, and you are not handling that.
In short, the easiest way to get rid of this is by returning if x is null:
var x = regEx.exec(element);
if (!x) return // add this
Tested it, and no problem was thrown, only console output was matched a

Related

How do I use indexOf to find a substring and then if it finds it set a value to another part of the array?

I'm working with date-related data (the code parses the dates after this code snippet), but due to some inconsistencies in the data I want to assign a value to the different dates. So if the date is complete it is assigned '0', and then two other levels '1' and '2'. So first I insert three new columns to the array with a default value, which works. But then I want to use indexOf to search for the dates with '00'. The '=== 5' is because it is searching for a substring of the full date 'YYYY-00-DD' and so on. I want the code to loop through the array and find these instances and when it does to assign the relevant number value to uncertainty (the someData[i]["uncertainty"] = 0;). I've been going round in circles trying to get it right so any help is gratefully received.
d3.csv('minimal.csv', function(error, someData) {
if (error) throw error;
console.log(someData);
// 1. add properties 'vstart' and 'vend' for inferred dates
// and uncertainty property
for (let i = 0; i < someData.length; i++) {
someData[i]["vstart"] = null;
someData[i]["vend"] = null;
someData[i]["uncertainty"] = 0;
};
/* 2. add 'uncertainty' levels:
0: no uncertainty, e.g. 1898-01-23
1: uncertainty in days, e.g. 1914-07-00
2: uncertainty in months e.g. 1906-00-00
*/
var uncertainty = someData.uncertainty;
for (let i = 0; i < someData.length; i++) {
if (someData.indexOf("00") === 5 ) { someData.uncertainty[i] = someData.uncertainty[i].replace(/0/i, 2); }
else if (someData.indexOf("00") === 8 ) { someData.uncertainty[i] = someData.uncertainty[i].replace(/0/i, 1); }
else if (someData.indexOf("00") === -1 ) { someData.uncertainty[i] = someData.uncertainty[i].replace(/0/i, 0); }
};
Created demo for you. Please check it.
You are trying to access array someData and apply indexOf() method. But this method will work on array element. So, you have to access array element by someData[i] and then apply the indexOf() method.
/* 2. add 'uncertainty' levels:
0: no uncertainty, e.g. 1898-01-23
1: uncertainty in days, e.g. 1914-07-00
2: uncertainty in months e.g. 1906-00-00
*/
var someData = [];
someData[0] = "1898-01-23";
someData[1] = "1914-07-00";
for (let i = 0; i < someData.length; i++) {
if (someData[i].indexOf("00") == 5 ) {
console.log("called 5");
}
else if (someData[i].indexOf("00") == 8 ) { console.log("called 8"); }
else if (someData[i].indexOf("00") == -1 ) { console.log("called -1"); }
};
for (let i = 0; i < someData.length; i++) {
const regex = /[0-9]+-([0-9]+)-([0-9]+)/gm;
let m;
while ((match = regex.exec(someData[i]["start"])) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (match.index === regex.lastIndex) {
regex.lastIndex++;
}
// month
if (match[1] === "00") {
someData[i]["uncertainty"] = someData[i]["uncertainty"].replace(/0/i, '1');
console.log('month', match[0])
}
else if (match[2] === "00") {
someData[i]["uncertainty"] = someData[i]["uncertainty"].replace(/0/i, '2');
console.log('day', match[0])
}
}
};

How to build a function that searches for string occurrences?

I need help Writing a function subLength() that takes 2 parameters, a string and a single character. The function should search the string for the two occurrences of the character and return the length between them including the 2 characters. If there are less than 2 or more than 2 occurrences of the character the function should return 0. How can I solve this problem using loops?
subLength('Saturday', 'a'); // returns 6
subLength('summer', 'm'); // returns 2
subLength('digitize', 'i'); // returns 0
subLength('cheesecake', 'k'); // returns 0
Here I loop through the characters of the string to find each value that is the char.
if the length isn't 2, return 0.
using slice, get only the characters within the two found indexs and get that length adding one to fix the offset
const subLength = (str, char) => {
let strChars = str.toLowerCase().split(""),
found = [],
length = 0;
strChars.forEach((val, index) => {
if (val === char) {
found.push(index);
}
});
if (found.length != 2) {
return length;
}
return str.slice(found[0], found[1]).length + 1;
}
console.log(subLength('Saturday', 'a')); // returns 6
console.log(subLength('summer', 'm')); // returns 2
console.log(subLength('digitize', 'i')); // returns 0
console.log(subLength('cheesecake', 'k')); // returns 0
You can try this logic:
Loop over string and count number of occurance
if count is 2,
Create a regex to capture the string in between.
Return its length
Else return 0
function subLength(str, char) {
let length = 0;
const occuranceCount = Array
.from(str)
.filter((c) => c.toLowerCase() === char.toLowerCase())
.length
if (occuranceCount === 2) {
const regex = new RegExp(`${char}(.*)${char}`)
length = str.match(regex)[0].length
}
console.log(length)
return length;
}
subLength('Saturday', 'a'); // returns 6
subLength('summer', 'm'); // returns 2
subLength('digitize', 'i'); // returns 0
subLength('cheesecake', 'k'); // returns 0
Using just for loop:
function subLength(str, char) {
let count = 0;
let initPosition;
let lastPosition;
for (let i = 0; i < str.length; i++) {
if (str[i] === char) {
count++
if (count > 2) {
return 0;
}
if (initPosition === undefined) {
initPosition = i
} else {
lastPosition = i+1
}
}
}
return count < 2 ? 0 : lastPosition - initPosition;
}
console.log(subLength('Saturday', 'a')); // returns 6
console.log(subLength('summer', 'm')); // returns 2
console.log(subLength('digitize', 'i')); // returns 0
console.log(subLength('cheesecake', 'k')); // returns 0
I too am going through the Codecademy course where this question came up which led me to this post.
Using the RegExp solution provided by #Rajesh (thank you!!) I started to break it down to better understand what was going on and making notes/comments because I am still pretty new and haven't used or been exposed to some of these things.
At the end of it all I thought I'd share what I ended up with in case anyone found it helpful.
function subLength(str, char) {
// Outputting to the console what we are looking for given the value of the string and character from the test cases at the end of this script.
console.log(`Showing the subLength for the string: "${str}" between "${char}" and "${char}" including the "${char}" positions.`);
// create the length variable which will be returned by the function
let length = 0;
// ** Search the string for the two occurrences of the character and count them. Then assign the result to the occurrenceCount variable for use in the if else statement.
// The "Array" class is a global object that is used in the construction off arrays.
// The Array.from() static method creates a new, shallow-copied Array instance from an array-like or iterable object.
// The Array.filter() method creates a new array with all elements that pass the test implemented by the provided function. The "c" represents each element of the array/string which is then compared to the char variable. if it is a match it gets added to the Array. We use .toLowerCase on both to ensure case compatibility.
// Appending the Array with ".length" assigns occurrenceCount the numeric value of the array's length rather than the array of characters.
const occurrenceCount = Array.from(str).filter((c) => c.toLowerCase() === char.toLowerCase());
console.log(' The contents of the occurrenceCountArray = ' + occurrenceCount);
console.log(' The character occurrence count = ' + occurrenceCount.length);
// if the string has two occurrences : return the length between them including the two characters : else the string has less than 2 or more than 2 characters : return 0.
if (occurrenceCount.length === 2) {
// The RegExp object is used for matching text with a pattern. The "(.*)" in between the ${char}'s will match and capture as much as possible aka greedy match. "()" = capture anything matched. (" = start of group. "." = match any character. "*" = Greedy match that matches everything in place of the "*". ")" = end of group.
const regex = new RegExp(`${char}(.*)${char}`);
// log to console the pattern being matched
console.log(` regex pattern to find = ${regex}`);
// log to the console the [0] = index 0 pattern that was captured from the string using str.match(regex)[0]
console.log(` regex output = ${str.match(regex)[0]}`);
// Use".length" to count the number of characters in the regex string at index 0 of the regex array and assign that value to the length variable.
length = str.match(regex)[0].length;
// Output the results to the console
console.log(` The distance from "${char}" to "${char}" (including the "${char}" positions) in the string: ${str} = ${length}\n`);
// return the length value
return length;
} else {
// Output the results to the console
console.log(` The string either has too many or too few occurrences.\n The subLength = ${length}\n`);
// return the length value
return length;
}
}
// test cases
subLength('Saturday', 'a'); // returns 6
subLength('summer', 'm'); // returns 2
subLength('digitize', 'i'); // returns 0
subLength('cheesecake', 'k'); // returns 0
The answer I am getting is this:
const subLength = (str, char) => {
let charCount = 0;
let len = -1;
for (let i=0; i<str.length; i++) {
if (str[i] == char) {
charCount++;
if (charCount > 2) {
return 0;
}
if (len == -1) {
len = i;
} else {
len = i - len + 1
}
}
}
if (charCount < 2) {
return 0;
}
return len;
};
It is better to try yourself a solution first. It is a very bad practice to just ask a solution for your homework!!!
Even if the solution can be JUST a few lines of code i wrote for you with commments a working solution :
const subLength = (str,char) => {
// create an empty array
const strarr = [];
// push string into array
strarr.push(str);
//initiate a count variable
let count = 0;
// WRITE YOUR REGULAR EXPRESSION
// Using the regular expression constructor - new RegExp("ab{2}", "g") .
const regString = `[${char}]`;
const regex = new RegExp(regString, "g");
// iterate through the string array to
for (let i = 0; i < strarr.length; i++) {
// calculate how many time the character occurs
count = (strarr[i].match(regex) || []).length;
};
// check with if condition
//if count is 2
if (count === 2) {
// calculate the index of first ocurrance of the string
first = str.indexOf(char);
// calculate the index of second ocurrance of the string
second = str.lastIndexOf(char);
// calculate the distance between them
return second - first + 1;
// if count is greater than two return 0
}
else if (count > 2) {
return count = 0;
}
// if count is less than two return 0
else if (count < 2) {
return 0;
}
};
console.log(subLength("iiiiliiile","l"));
I just answered this problem in codeAcademy and this is the solution that I came up with, just using if-statements and string.indexOf
const subLength = (strng, char) => {
let firstIndex = strng.indexOf(char);
let secondIndex = strng.indexOf(char, (firstIndex + 1));
let thirdIndex = strng.indexOf(char, (secondIndex + 1));
if (firstIndex === -1){
return 0
} else if (secondIndex === -1){
return 0
} else if (thirdIndex === -1 ){
return (secondIndex - firstIndex + 1)
} else {
return 0
};
};

Check for Partial Match in an Array

I have a JavaScript array that contains some words that cannot be used when requesting user accounts to be created.
I am trying to loop over the accounts requested and check them against a word filter. If they contain any of the words, the value is moved to an array of "Invalid Accounts".
// Create our arrays
var blacklist = ["admin", "webform", "spoof"];
var newAccounts = ["admin1#google.com", "interweb#google.com", "puppy#google.com"];
var invalidAccounts = [];
// I need to check if any of the new accounts have matches to those in the blacklist.
// admin1#google.com would need to be pushed into the invalidAccounts array because it
// contains the word admin. Although interweb contains the word web, it does not contain
// the full word, webform, so should be ignored.
// Loop over the blacklist array
for(var x = 0; x < blacklist.length; x++){
if(blacklist[x].indexOf(newAccounts) > -1){
alert(blacklist[x] + " is in the blacklist array");
// Push the newAccounts value into the invalidAccounts array since it contains
// a blacklist word.
} else {
alert('no matches');
}
}
What do I need to change in the above code to have it match the partial strings such as mentioned?
Fiddle of above code: https://jsfiddle.net/1qwze81o/
You probably won't need to use all of this but it should be helpful none the less:
var blacklist = ["admin", "webform", "spoof"];
var newAccounts = ["admin1#google.com", "interweb#google.com", "puppy#google.com"];
var invalidAccounts = [];
// transform each email address to an object of the form:
// { email: string, valid: boolean }
var accountObjects = newAccounts.map(function (a) {
return { email: a, valid: true };
});
// loop over each account
accountObjects.forEach(function (account) {
// loop over the blacklisted terms
blacklist.forEach(function (blacklisted) {
// check to see if your account email address contains a black listed term
// and set the valid property accordingly
account.valid = account.email.search(blacklisted) === -1;
});
});
// filter accountObjects, validAccounts will now contain an array of valid objects
var validAccounts = accountObjects.filter(function (a) {
return a.valid;
});
// back to the original type of a string array
var validEmailAddresses = validAccounts.map(function (a) {
return a.email;
});
A solution using javascript array native functions:
var invalidAccounts = newAccounts.filter(function(account){ // we need to filter accounts
return blacklist.some(function(word){ // and return those that have any of the words in the text
return account.indexOf(word) != -1
})
});
More info on: Array.filter and
Array.some
We need two loops to achieve this:
something like below:
// Loop over the blacklist array
for(var j = 0; x < newAccounts.length; j++){
for(var x = 0; x < blacklist.length; x++){
if(newAccounts[j].indexOf(blacklist[x]) > -1){
alert(blacklist[x] + " is in the blacklist array");
// Push the newAccounts value into the invalidAccounts array since it contains a blacklist word.
}else{
alert('no matches');
}
}
}
I fixed some of the things...
for (var x = 0; x < newAccounts.length; x++) // loop through new accounts
{
// for every account check if there is any match in blacklist array
for (var y = 0; y < blacklist.length; y++)
{
// if there is match do something
if (newAccounts[x].indexOf(blacklist[y]) > -1)
{
alert(newAccounts[x] + " is in the blacklist array");
break;
}
}
}
Here is the fiddle: https://jsfiddle.net/swaprks/n1rkfuzh/
JAVASCRIPT:
// Create our arrays
var blacklist = ["admin", "webform", "spoof"];
var newAccounts = ["admin1#google.com", "interweb#google.com", "puppy#google.com"];
var invalidAccounts = [];
for(var x = 0; x < newAccounts.length; x++){
for(var y = 0; y < blacklist.length; y++){
if( newAccounts[x].indexOf(blacklist[y]) > -1){
alert(blacklist[x] + " is in the blacklist array");
// Push the newAccounts value into the invalidAccounts array since it contains
// a blacklist word.
invalidAccounts.push(newAccounts[x]);
}else{
alert('no matches');
}
}
}

JS function to validate input name not working correctly

The objective of this code is to check the name the user inputs. If the value contains something other than -abcdefghijklmnopqrstuvwxyz'ABCDEFGHIJKLMNOPQRSTUVWXYZ the function will throw an error.
I am unable to get this to work, and I'm not allowed to use Regular expressions. I've also tried String1.indexOf(usr.substr(i,1)) > -1) but that doesn't seem to work neither.
function nameValidation(username) {
var usr = document.getElementById("username").value;
usr = usr.trim();
var alpha = "-abcdefghijklmnopqrstuvwxyz'ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var ok = 1;
for (var i = 0; i < usr.length; i++) {
if (!isNaN(usr[i])) {
ok = 0;
break;
} else {
ok = 1;
document.getElementById("fnerror").innerHTML = "";
document.getElementById("username").style.borderColor = "lightgrey";
return true;
}
}
if (ok == 0) {
document.getElementById("fnerror").innerHTML = "X Enter Upper and lower case letters, hypen, apostrohe only please";
return false;
}
return true;
}
Something like this, maybe:
function isValidUsername(username) {
var alpha = "-'ABCDEFGHIJKLMNOPQRSTUVWXYZ";
username = username.toUpperCase();
for (var i = 0, l = username.length; i < l; i++) {
if (alpha.indexOf(username[i]) === -1) return false;
}
return true;
}
Cheaper to upper-case the string and therefore have a shorter set of characters to test against (though probably marginal at best because there's a cost to even native-uppercasing..)
You can do it in a more "functional way", by using every method, which allow us to break a loop instead of foreach.
The every method executes the provided callback function once for each element present in the array until it finds one where callback returns a falsy value (a value that becomes false when converted to a Boolean). If such an element is found, the every method immediately returns false. Otherwise, if callback returned a true value for all elements, every will return true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
Array.proototype.every
So :
function check(){
//Get value input and transform it into array
var value = document.querySelector('#username').value.split('');
var alpha = "-abcdefghijklmnopqrstuvwxyz'ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//If there is an error, stop the loop and return result
return value.every(function(elm){
//check if elm is an alpha string
return alpha.indexOf(elm) > -1;
});
}
The easiest (to understand at least) solution (that doesn't use regex), would be to loop through your string character by character and check .indexOf against your list of allowed characters, something like:
for (var i = 0; i < input.length; i++) {
if (alpha.indexOf(input[i])==-1) {
console.log("ERROR");
break;
}
}
EDITED: I read the question wrong and thought you wanted to return true if there's a letter. It will now make sure that each character is within the ASCII values of A and z.
text = "ABCDEFzzxasd1";
valid = true;
for( i = 0; i < text.length; i++ ) {
if ( text.charCodeAt(i) < 65 || text.charCodeAt(i) > 122 ) {
alert("Woah, that's not a letter!");
valid = false;
break;
}
}
Begin with
var alpha = "-abcdefghijklmnopqrstuvwxyz'ABCDEFGHIJKLMNOPQRSTUVWXYZ".split('');
function duplicates( element, index, array ){
return array.indexOf(element) == index;
}
function isNameFormatCorrect( userName ){
return ( alpha.concat(username.split(''))
.filter( duplicates ).length === alpha.length );
}
Then
var username = "YourUserNameHere-"
isNameFormatCorrect( username ); => true;
var username = "YourUserNameHere-**"
isNameFormatCorrect( username ); => false;

remove value from comma separated values string

I have a csv string like this "1,2,3" and want to be able to remove a desired value from it.
For example if I want to remove the value: 2, the output string should be the following:
"1,3"
I'm using the following code but seems to be ineffective.
var values = selectedvalues.split(",");
if (values.length > 0) {
for (var i = 0; i < values.length; i++) {
if (values[i] == value) {
index = i;
break;
}
}
if (index != -1) {
selectedvalues = selectedvalues.substring(0, index + 1) + selectedvalues.substring(index + 3);
}
}
else {
selectedvalues = "";
}
var removeValue = function(list, value, separator) {
separator = separator || ",";
var values = list.split(separator);
for(var i = 0 ; i < values.length ; i++) {
if(values[i] == value) {
values.splice(i, 1);
return values.join(separator);
}
}
return list;
}
If the value you're looking for is found, it's removed, and a new comma delimited list returned. If it is not found, the old list is returned.
Thanks to Grant Wagner for pointing out my code mistake and enhancement!
John Resign (jQuery, Mozilla) has a neat article about JavaScript Array Remove which you might find useful.
function removeValue(list, value) {
return list.replace(new RegExp(",?" + value + ",?"), function(match) {
var first_comma = match.charAt(0) === ',',
second_comma;
if (first_comma &&
(second_comma = match.charAt(match.length - 1) === ',')) {
return ',';
}
return '';
});
};
alert(removeValue('1,2,3', '1')); // 2,3
alert(removeValue('1,2,3', '2')); // 1,3
alert(removeValue('1,2,3', '3')); // 1,2
values is now an array. So instead of doing the traversing yourself.
Do:
var index = values.indexOf(value);
if(index >= 0) {
values.splice(index, 1);
}
removing a single object from a given index.
hope this helps
Here are 2 possible solutions:
function removeValue(list, value) {
return list.replace(new RegExp(value + ',?'), '')
}
function removeValue(list, value) {
list = list.split(',');
list.splice(list.indexOf(value), 1);
return list.join(',');
}
removeValue('1,2,3', '2'); // "1,3"
Note that this will only remove first occurrence of a value.
Also note that Array.prototype.indexOf is not part of ECMAScript ed. 3 (it was introduced in JavaScript 1.6 - implemented in all modern implementations except JScript one - and is now codified in ES5).
// Note that if the source is not a proper CSV string, the function will return a blank string ("").
function removeCsvVal(var source, var toRemove) //source is a string of comma-seperated values,
{ //toRemove is the CSV to remove all instances of
var sourceArr = source.split(","); //Split the CSV's by commas
var toReturn = ""; //Declare the new string we're going to create
for (var i = 0; i < sourceArr.length; i++) //Check all of the elements in the array
{
if (sourceArr[i] != toRemove) //If the item is not equal
toReturn += sourceArr[i] + ","; //add it to the return string
}
return toReturn.substr(0, toReturn.length - 1); //remove trailing comma
}
To apply it too your var values:
var values = removeVsvVal(selectedvalues, "2");
guess im too slow but here is what i would do
<script language="javascript">
function Remove(value,replaceValue)
{ var result = ","+value+",";
result = result.replace(","+replaceValue+",",",");
result = result.substr(1,result.length);
result = result.substr(0,result.length-1);
alert(result);
}
Remove("1,2,3",2)
</script>
adding , before and after the string ensure that u only remove the exact string u want
function process(csv,valueToDelete) {
var tmp = ","+csv;
tmp = tmp.replace(","+valueToDelete,"");
if (tmp.substr(0,1) == ',') tmp = tmp.substr(1);
return tmp;
}
use splice, pop or shift. depending on your requirement.
You could also have "find" the indexes of items in your array that match by using a function like the one found here : http://www.hunlock.com/blogs/Ten_Javascript_Tools_Everyone_Should_Have
var tmp = [5,9,12,18,56,1,10,42,'blue',30, 7,97,53,33,30,35,27,30,'35','Ball', 'bubble'];
// 0/1/2 /3 /4/5 /6 /7 /8 /9/10/11/12/13/14/15/16/17/ 18/ 19/ 20
var thirty=tmp.find(30); // Returns 9, 14, 17
var thirtyfive=tmp.find('35'); // Returns 18
var thirtyfive=tmp.find(35); // Returns 15
var haveBlue=tmp.find('blue'); // Returns 8
var notFound=tmp.find('not there!'); // Returns false
var regexp1=tmp.find(/^b/); // returns 8,20 (first letter starts with b)
var regexp1=tmp.find(/^b/i); // returns 8,19,20 (same as above but ignore case)
Array.prototype.find = function(searchStr) {
var returnArray = false;
for (i=0; i<this.length; i++) {
if (typeof(searchStr) == 'function') {
if (searchStr.test(this[i])) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
} else {
if (this[i]===searchStr) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
}
}
return returnArray;
}
or
var csv_remove_val = function(s, val, sep) {
var sep = sep || ",", a = s.split(sep), val = ""+val, pos;
while ((pos = a.indexOf(val)) >= 0) a.splice(pos, 1);
return a.join(sep);
}

Categories

Resources