Javascript jQuery: find array elements within a string - javascript

I think my question is fairly straightforward but I'm not very experienced with Javascript. What I am trying to do is pull the source code of a page and stick it all into a variable:
var sourcecode = document.documentElement.innerHTML;
Then I have an array of terms that I want to search that variable for:
var array = ['Huskers','Redskins','Texans','Rockets'];
I would like to assign a 0 to any of the array elements that aren't found in the sourcecode variable and a 1 to any that are. So, when the search is complete each array element will be represented by a variable that will either equal 1 or 0. Can anyone please give me a hint as to how I should go about this?
Thanks!

A bit cryptic but does what you need:
var source = 'lorem hello foo bar world';
var words = ['hello','red','world','green'];
words = words.map(function(w){ return +!!~source.indexOf(w) });
console.log(words); //=> [1, 0, 1, 0]
+!!~ casts a number of the boolean representation of the value returned by indexOf, same as:
return source.indexOf(w) == -1 ? 0 : 1;
But a bit shorter.
Note that indexOf matches strings within strings as well, if you want to match whole words you can use regex with word boundaries \b:
words = words.map(function(w) {
return +new RegExp('\\b'+ w +'\\b','gi').test(source);
});

If you want to find element in array you can use jquery $.inArray()
http://jsfiddle.net/hgHy4/
$(document).ready(function() {
var array = ['Huskers','Redskins','Texans','Rockets'];
alert($.inArray('Redskins', array));
});
This will returns index number of element inside an array if it is found. If the element is not found it will return -1

Related

Dynamic string cutting

Okay, so I have a filepath with a variable prefix...
C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade
... now this path will be different for whatever computer I'm working on...
is there a way to traverse the string up to say 'secc-electron\', and drop it and everything before it while preserving the rest of it? I'm familiar with converting strings to arrays to manipulate elements contained within delimiters, but this is a problem that I have yet to come up with an answer to... would there be some sort of regex solution instead? I'm not that great with regex so I wouldn't know where to begin...
What you probably want is to do a split (with regex or not):
Here's an example:
var paragraph = 'C:\\Users\\susan ivey\\Documents\\VKS Projects\\secc-electron\\src\\views\\main.jade';
var splittedString = paragraph.split("secc-electron"); // returns an array of 2 element containing "C:\\Users\\susan ivey\\Documents\\VKS Projects\\" as the first element and "\\src\\views\\main.jade" as the 2nd element
console.log(splittedString[1]);
You can have a look at this https://www.w3schools.com/jsref/jsref_split.asp to learn more about this function.
With Regex you can do:
var myPath = 'C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade'
var relativePath = myPath.replace(/.*(?=secc-electron)/, '');
The Regex is:
.*(?=secc-electron)
It matches any characters up to 'secc-electron'. When calling replace it will return the last part of the path.
You can split the string at a certain point, then return the second part of the resulting array:
var string = "C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade"
console.log('string is: ', string)
var newArray = string.split("secc-electron")
console.log('newArray is: ', newArray)
console.log('newArray[1] is: ', newArray[1])
Alternatively you could use path.parse(path); https://nodejs.org/api/path.html#path_path_parse_path and retrieve the parts that you are interested in from the object that gets returned.

Javascript: given an array of variables, function to remove characters and output another array

so I am still learning Javascript, so I know this is a basic questions, and I'd really like to learn what I'm missing. I have an array of variables, and I need a function that removes special characters, and returns the result as an array.
Here's my code:
var myArray = [what_hap, desc_injury];
function ds (string) {
string.replace(/[\\]/g, ' ')
string.replace(/[\"]/g, ' ')
string.replace(/[\/]/g, '-')
string.replace(/[\b]/g, ' ')
string.replace(/[\f]/g, ' ')
string.replace(/[\n]/g, ',')
string.replace(/[\r]/g, ' ')
string.replace(/[\t]/g, ' ');
return string;
}
ds (myArray);
I know that's not going to work, so I'm just trying to learn the simplest and cleanest way to output:
[whatHap: TEXTw/oSpecialCharacters, descInj: TEXTw/oSpecialCharacters]
Anyone willing to guide a noobie? Thanks! :)
The comments on the question are correct, you need to specify what you are asking a little better but I will try and give you some guidance from what I assume about your intended result.
One important thing to note which would fix the function you already have is that string.replace() will not change the string itself, it returns a new string with the replacements as you can see in the documentation. to do many replacements you need to do string = string.replace('a', '-')
On to a solution for the whole array. There are a couple ways to process an array in javascript: for loop, Array.forEach(), or Array.map(). I urge you to read the documentation of each and look up examples on your own to understand each and where they are most useful.
Since you want to replace everything in your array I suggest using .map()
or .foreach() since these will loop through the whole array for you without you having to keep track of the index yourself. Below are examples of using each to implement what I think you are going for.
Map
function removeSpecial(str) {
// replace all these character with ' '
// \ " \b \f \r \t
str = str.replace(/[\\"\b\f\r\t]/g, ' ');
// replace / with -
str = str.replace(/\//g, '-');
// replace \n with ,
str = str.replace(/\n/g, ',');
return str;
}
let myArray = ["string\\other", "test/path"];
let withoutSpecial = myArray.map(removeSpecial); // ["string other", "test-path"]
forEach
function removeSpecial(myArray) {
let withoutSpecial = [];
myArray.forEach(function(str) {
str = str.replace(/[\\"\b\f\r\t]/g, ' ');
// replace / with -
str = str.replace(/\//g, '-');
// replace \n with ,
str = str.replace(/\n/g, ',');
withoutSpecial.push(str)
});
return withoutSpecial;
}
let myArray = ["string\\other", "test/path"];
let withoutSpecial = removeSpecial(myArray); // ["string other", "test-path"]
The internalals of each function's can be whatever replacements you need it to be or you could replace them with the function you already have. Map is stronger in this situation because it will replace the values in the array, it's used to map the existing values to new corresponding values one to one for every element. On the other hand the forEach solution requires you to create and add elements to a new array, this is better for when you need to do something outside the array itself for every element in the array.
PS. you should check out https://regex101.com/ for help building regular expressions if you want a more complex replacements but you dont really need them for this situation
I realize that the way I wrote my goal isn't exactly clear. I think what I should have said was that given several text strings, I want to strip out some specific characters (quotes, for example), and then output each of those into an array that can be accessed. I have read about arrays, it's just been my experience in learning JS that reading code and actually doing code are two very different things.
So I appreciate the references to documentation, what I really needed to see was a real life example code.
I ended up finding a solution that works:
function escapeData(data) {
return data
.replace(/\r/g, "");
}
var result = {};
result.what_hap_escaped = escapeData($what_hap);
result.desc_injury_escaped = escapeData($desc_injury);
result;
I appreciate everyone's time, and hope I didn't annoy you guys too much with my poorly constructed question :)

how to get the length of the given web element in protractor tests

I would like to find out the length of the variable which I get from the screen. If I use
var driverID = element(by.id('driverID')).getAttribute('value')
driverID.length
it is throwing and error as Property 'length' does not exist on type'Promise <string>. Can some one help me in finding the length of the string.
I would also like to know how to use string operations in protractor tests. In this case I want to know, if the string first index is 'character or a number' and the second index is 'character or a number'. I want to do this by using the length of the string.
use the count() method for the number of elements inside a Promise.
Now for your specific problem, you should do something like:
element(by.id('driverID')).getAttribute('value').then(function(attr) {
var length = attr.length; // I don't really need why you need this length
if (!isNaN(attr[0]) && !isNaN(attr[1])) {
// 1st and 2nd characters of the string are numbers.
}
})
try that:
var driverID = element(by.id('driverID')).getAttribute('value');
driverID.then((attribute) => {
console.log(attribute.length)
});
the second issue you can resolve using regex

JavaScript - split, choose all after a given number

I have an dynamic array and I want to exclude the first part of the string, but I don't know how many objects there will be after the first part and I want to include them all in a new string.
string = "text.'''hi''','''who''' '''are''' '''you'''. I'm ken and you're barbie"
x = string.split("'''")[1]
Is there something I can do to include them all? like [1..?]
I have JQuery but don't think that would be necessary right?
shift:
Removes the first element from an array and returns that element. This method changes the length of the array.
Code:
x = theString.split("'''");
var firstElement = x.shift();
// Now x is the shifted array.
x[0];
You seem to want:
x = string.split("'''").slice(1);
This will return all elements of the array starting at index 1.

javascript regex help

i am trying to validate if a certain company was already picked for an application. the companyList format is:
60,261,420 ( a list of companyID)
I used
cID = $('#coName').val().split('::')[1];
to get the id only.
I am calling this function by passing say 60:
findCompany = function(value) {
var v = /^.+60,261,420$/.test(value);
alert(v);
}
when I pass the exact same string, i get false. any help?
Well if your company list is a list of numeric IDs like that, you need to make the resulting regular expression actually be the correct expression — if that's even the way you want to do it.
Another option is to just make an array, and then test for the value being in the array.
As a regex, though, what you could do is this:
var companyList = [<cfoutput> whatever </cfoutput>]; // get company ID list as an array of numbers
var companyRegex = new RegExp("^(?:" + companyList.join('|') + ")$");
Then you can say:
function findCompany(id) {
if (companyRegex.test(id)) alert(id + " is already in the list!");
}
Why not split the string into an array, like you did for your testing, iterate over the list and check if it's in?
A regexp just for that is balls, overhead and slower. A lot.
Anyway, for your specific question:
You’re checking the string "60" for /^.+60,261,420$/.
.+60 will obviously not match because you require at least one character before the 60. The commas also evaluate and are not in your String.
I don’t quite get where your regexp comes from.
Were you looking for a regexp to OR them a hard-coded list of IDs?
Code for splitting it and checking the array of IDs:
findCompany = function(value) {
$('#coName').val().split('::').each(function(val){
if(val == value) return true;
});
return false;
}

Categories