I'm a Javascript noob using regex in javascript to globally replace text on web page. Easy enough.
v = v.replace(/\Simon\b/g, "JS Noob");
I know I can replace with functions, but I can't get this to work:
v = v.replace(/\bSimon\b/g, function(replaceLoop) {
var myStringArray = ["herp","derp","clueless","hurrrrr"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++){
replaceLoop = myStringArray;
return replaceLoop;
}
}
I have a feeling I'm thinking about this all wrong.
Step 1, make a function which returns the next item from an Array each time
function iterGen(arr, i) {
i || (i = 0);
return function () {
i %= arr.length;
return arr[i++];
};
}
Step 2, pass this into your replace
v = v.replace(/\bSimon\b/g, iterGen(["herp","derp","clueless","hurrrrr"]));
A quick syntax error is causing issues, you are missing the closing ); to .replace(). Also, you are setting replaceLoop = myStringArray instead of a specific string. Assuming you want a random index, you'll need Math.random().
v = v.replace(/\bSimon\b/g, function(replaceLoop) {
var myStringArray = ["herp","derp","clueless","hurrrrr"];
var arrayLength = myStringArray.length;
var index = Math.floor(Math.random() * arrayLength);
return myStringArray[index];
});
Related
Javascript program has something wrong ,I don't know why the length of log is not 10?
the input s :
const s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
var findRepeatedDnaSequences = function(s) {
var set = new Set()
var seqSet = new Set()
for (let i = 0; i < s.length - 11; i++) {
let sub = s.substr(i, i + 10)
console.log(sub)
if (set.has(sub)) {
seqSet.add(sub)
} else {
set.add(sub)
}
}
return Array.from(set)
};
findRepeatedDnaSequences(s)
the console result:Javascript program has something wrong ,I don't know why the length of log is not 10?
AAAAACCCCC
AAAACCCCCAA
AAACCCCCAAAA
AACCCCCAAAAAC
ACCCCCAAAAACCC
CCCCCAAAAACCCCC
CCCCAAAAACCCCCCA
CCCAAAAACCCCCCAAA
CCAAAAACCCCCCAAAAA
CAAAAACCCCCCAAAAAGG
AAAAACCCCCCAAAAAGGGT
AAAACCCCCCAAAAAGGGTTT
AAACCCCCCAAAAAGGGTTT
AACCCCCCAAAAAGGGTTT
ACCCCCCAAAAAGGGTTT
CCCCCCAAAAAGGGTTT
CCCCCAAAAAGGGTTT
CCCCAAAAAGGGTTT
CCCAAAAAGGGTTT
CCAAAAAGGGTTT
CAAAAAGGGTTT
The arguments you're giving to substr() are appropriate for substring(). Since substr() is deprecated, you should just change to substring() and you'll get the results you want.
const s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
var findRepeatedDnaSequences = function(s) {
var set = new Set()
var seqSet = new Set()
for (let i = 0; i < s.length - 11; i++) {
let sub = s.substring(i, i + 10)
console.log(sub)
if (set.has(sub)) {
seqSet.add(sub)
} else {
set.add(sub)
}
}
return Array.from(set)
};
findRepeatedDnaSequences(s)
substr takes a starting offset and a length. You should call just .substr(i, 10).
const s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
var findRepeatedDnaSequences = function(s) {
var set = new Set()
var seqSet = new Set()
for (let i = 0; i < s.length - 11; i++) {
let sub = s.substr(i, 10)
console.log(sub)
if (set.has(sub)) {
seqSet.add(sub)
} else {
set.add(sub)
}
}
return Array.from(set)
};
findRepeatedDnaSequences(s)
in js there are 2 functions:
substr():
The substr() method returns a portion of the string, starting at the
specified index and extending for a given number of characters
afterwards.
substring().
The substring() method returns the part of the string between the
start and end indexes, or to the end of the string.
you are using the 1st one, and from your question, you are expecting the 2nd.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring.
I have an algorithm where the user will enter a string and I will parse it into an array of 2+ dimensions. So, for example, the user can enter 1,2,3;4,5,6 and set the text to be parsed by the semicolon and the comma. The first pass through will create an array with 2 entries. The second pass through will create a 3 entry array in both prior spots.
The user can add or remove the number of text items to be used to parse the original string such as the semicolon or comma, meaning the resulting array can have as many dimensions as parsing items.
This doesn't seem like a difficult problem, but I have run into some snags.
Here is my code so far.
vm.parsers = [';', ','];
vm.inputString = "1,2,3,4,5;6,7,8,9,10";
function parseDatasetText( )
{
vm.real = vm.parseMe( vm.inputString, 0);
};
function parseMe( itemToParse, indexToParse )
{
if ( indexToParse < vm.parsers.length )
{
console.log('Parsing *'+itemToParse+'* with '+vm.parsers[indexToParse]);
var tempResults = itemToParse.split( vm.parsers[indexToParse] );
for (var a=0; a<tempResults.length; a++)
{
console.log('Pushing '+tempResults[a]);
tempResults[a] = vm.parseMe( tempResults[a], parseInt( indexToParse ) + 1 )
console.log('This value is '+tempResults[a]);
}
}else
{
console.log('Returning '+itemToParse);
return itemToParse
}
};
As you can see from the console logs, the algorithm spits out an undefined after the last parse, and the final answer is undefined.
Maybe I just haven't slept enough, but I was thinking that the array would recursively populate via the splits?
Thanks
function parseDatasetText(){
//composing parser from right to left into a single function
//that applies them from left to right on the data
var fn = vm.parsers.reduceRight(
(nextFn, delimiter) => v => String(v).split(delimiter).map(nextFn),
v => v
);
return fn( vm.inputString );
}
Don't know what else to add.
You can use a simple recursive function like the following (here an example with 3 different delimiters):
function multiSplit(xs, delimiters) {
if (!delimiters.length) return xs;
return xs.split(delimiters[0]).map(x => multiSplit(x, delimiters.slice(1)));
}
data = '1:10,2:20,3:30;4:40,5:50,6:60';
res = multiSplit(data, [';', ',', ':']);
console.log(res)
The following function should suit your requirements, please let me know if not
var parsers = [';', ',', ':'],
inputString = "1:a,2:b,3:c,4:d,5:e;6:f,7:g,8:h,9:i,10:j",
Result = [];
function Split(incoming) {
var temp = null;
for (var i = 0; i < parsers.length; i++)
if (incoming.indexOf(parsers[i]) >= 0) {
temp = incoming.split(parsers[i]);
break;
}
if (temp == null) return incoming;
var outgoing = [];
for (var i = 0; i < temp.length; i++)
outgoing[outgoing.length] = Split(temp[i])
return outgoing;
}
Result = Split(inputString);
try it on https://jsfiddle.net/cgy7nre1/
Edit 1 -
Added another inputString and another set of parsers: https://jsfiddle.net/cgy7nre1/1/
Did you mean this?
var inputString = "1,2,3,4,5;6,7,8,9,10";
var array=inputString.split(';');
for (var i=0;i<array.length;i++){
array[i]=array[i].split(',');
}
console.log(array);
So, I have following js setup:
var NAMES = [];
function INFO(id,first,middle,last){
var newMap = {};
newMap[id] = [first, middle, last];
return newMap ;
}
Then,
for (var j = 0; j < NUMBER.length; j++) { //let say it there are three values
var my_name = all_names[j]; // has "185, 185, 185"
if (NAMES[my_name] !== 185){ //Needs to check here
NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));
}else{
}
}
alert(JSON.stringify(NAMES , null, 4));
Here is a screenshot of the alert:
I hardcoded the number "185" for this example. I need to check if the id of 185 exists, then skip to else. I am not sure how to check it. I tried typeof, undefinedetc. but no luck.
(In other words, I should only have one "185").
Any help? Thanks!
If I understood correctly what you are trying to achieve, you have to iterate over NAMES and check every element. For example, you could do it using [].some javascript function:
if (!NAMES.some(function(v){return v[my_name]})) {
...
} else {
}
If you want to remove duplication you can just use NAMES as an object instead of array like this
var all_names = [185, 185, 181],
NAMES = {};
for (var j = 0; j < all_names.length; j++) { //let say it there are three values
var my_name = all_names[j]; // has "185, 185, 185"
NAMES[my_name] = ["sean","sdfsd","sdfsfd"];
}
alert(JSON.stringify(NAMES, null, 4));
First of all I would recommend making a JS Fiddle or CodePen out of this so people can see the code running.
I believe that the issue is that NAMES[my_name] is not doing what you think it is. NAMES is an Array so when you say NAMES[my_name] you are really asking for the ITEM in the array so you are getting the entire object that you create in the INFO function. What you really want is to see if the object has an attribute that matches the value (e.g. "185" from the my_names array).
This is not the prettiest code but it will show you how to do what you really want to do:
var NAMES = [];
function INFO(id,first,middle,last){
var newMap = {};
newMap[id] = [first, middle, last];
return newMap ;
}
all_names = ["185", "186", "185"]
for (var j = 0; j < all_names.length; j++) {
var my_name = all_names[j];
if (NAMES.length == 0) {
NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));
} else {
var match = false;
for (var x = 0; x < NAMES.length; x++) {
console.log(NAMES[x][my_name] + ' : ' + my_name);
if(NAMES[x][my_name]) {
match = true;
}
}
if (!match) {
NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));
}
}
}
alert(JSON.stringify(NAMES , null, 4));
Note the if that looks at NAMES[x][my_name] - this is asking if the item at array index 'x' has an attribute of 'my_name' (e.g. "185"). I believe this is really what you are trying to do. As its after midnight I assure you that there is more concise and pretty JS to do this but this should show you the basic issue you have to address.
Try this code using hasOwnProperty method :
for (var j = 0; j < NUMBER.length; j++) { //let say it there are three values
var my_name = all_names[j]; // has "185, 185, 185"
if (!NAMES[my_name].hasOwnProperty("185")){ //Needs to check here
NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));
}else{
}
}
I have been searching online all day and I cant seem to find my answer. (and I know that there must be a way to do this in javascript).
Basically, I want to be able to search through an array of objects and return the object that has the information I need.
Example:
Each time someone connects to a server:
var new_client = new client_connection_info(client_connect.id, client_connect.remoteAddress, 1);
function client_connection_info ( socket_id, ip_address, client_status) {
this.socket_id=socket_id;
this.ip_address=ip_address;
this.client_status=client_status; // 0 = offline 1 = online
};
Now, I want to be able to search for "client_connection.id" or "ip_address", and bring up that object and be able to use it. Example:
var results = SomeFunction(ip_address, object_to_search);
print_to_screen(results.socket_id);
I am new to javascript, and this would help me dearly!
Sounds like you simply want a selector method, assuming I understood your problem correctly:
function where(array, predicate)
{
var matches = [];
for(var j = 0; j < array.length; j++)
if(predicate(j))
matches.push(j);
return matches;
}
Then you could simply call it like so:
var sample = [];
for(var j = 0; j < 10; j++)
sample.push(j);
var evenNumbers = where(sample, function(elem)
{
return elem % 2 == 0;
});
If you wanted to find a specific item:
var specificguy = 6;
var sixNumber = where(sample, function(elem)
{
return elem == specificguy;
});
What have you tried? Have you looked into converting the data from JSON and looking it up as you would in a dictionary? (in case you don't know, that would look like object['ip_address'])
jQuery has a function for this jQuery.parseJSON(object).
You're going to need to loop through your array, and stop when you find the object you want.
var arr = [new_client, new_client2, new_client3]; // array of objects
var found; // variable to store the found object
var search = '127.0.0.1'; // what we are looking for
for(var i = 0, len = arr.length; i < len; i++){ // loop through array
var x = arr[i]; // get current object
if(x.ip_address === search){ // does this object contain what we want?
found = x; // store the object
break; // stop looping, we've found it
}
}
I have a string like this:
string = "locations[0][street]=street&locations[0][street_no]=
34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";
What must I do with this string so i can play with locations[][] as I wish?
You could write a parser:
var myStr = "locations[0][street]=street&locations[0][street_no]=34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";
function parseArray(str) {
var arr = new Array();
var tmp = myStr.split('&');
var lastIdx;
for (var i = 0; i < tmp.length; i++) {
var parts = tmp[i].split('=');
var m = parts[0].match(/\[[\w]+\]/g);
var idx = m[0].substring(1, m[0].length - 1);
var key = m[1].substring(1, m[1].length - 1);
if (lastIdx != idx) {
lastIdx = idx;
arr.push({});
}
arr[idx * 1][key] = parts[1];
}
return arr;
}
var myArr = parseArray(myStr);
As Shadow wizard said, using split and eval seems to be the solution.
You need to initialize locations first, if you want to avoid an error.
stringArray=string.split("&");
for (var i=0;i<stringArray.length;i++){
eval(stringArray[i]);
}
However, you might need to pay attention to what street and street_no are.
As is, it will produce an error because street is not defined.
Edit: and you'll need to fully initialize locations with as many item as you'll have to avoid an error.