hello I would like to build an array that every element will be a pair of objects , Something like this
var Shelves = new arr[][]
var books = new Books[] ;
Shelves[book[i],book[j=i+1]],[book[i+1],book[j=i+1]] and so on......;
I mean that I understand how to go with a for loop and to get the elements 'but how to push them in pairs array? arr.push doesn't work :(
build1ArrPairs(1Arr) {
if (1Arr != undefined || 1Arr!=null) {
for (var i = 0; i < 1Arr.length; i = i + 1) {
for (var j = i + 1; j <= 1Arr.length; j++) {
this.1ArrPair.push(1Arr[i] 1Arr[j]);
break;
}
}
}
}
Thanks :)
Alternatively, you can use array#reduce to group your array.
var names = ['a', 'b','c','d','e'];
var result = names.reduce((r,w,i) => {
let index = Math.floor(i/2);
if(!Array.isArray(r[index]))
r[index] = [];
r[index].push(w);
return r;
},[]);
console.log(result);
First of all, variables names can't start with a number.
Second, initialize an array, then add your elements - two at a time - and return the array:
var ans = [];
if (Arr != undefined || Arr != null) {
for (var i=0; i<(Arr.length-1); i+=2) { // Note the loop stops 2 elements before the last one
ans.push([Arr[i], Arr[i+1]]);
// ^ Note the comma - it's missing in your code
}
}
return ans;
I have a string "Hello World". I want the positions of the char "l" from the String.
My code is the following:
str = "Hello World";
pos = str.search(/l/g);
out.value = pos;
The result of this code is 2, but the wanted result is 2,3,9.
How can i get this result?
Edit: thanks for your help.
But now i want to get the sum of (2+1*105) + (3+1*105) + (9+1*105).
Can you help me again?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
Finding successive matches
If your regular expression uses the "g" flag, you can use the exec()
method multiple times to find successive matches in the same string.
When you do so, the search starts at the substring of str specified by
the regular expression's lastIndex property (test() will also advance
the lastIndex property).
var str = "Hello World";
var re = /l/g;
var matches = [];
while(match=re.exec(str)) matches.push(match.index);
document.write(matches);
What about a small function to do it?
str = "Hello World";
find = (function(str,c){
results = []
for(i=0;i<str.length;i++){
if (str[i].toLowerCase()===c)
results.push(i)
}
return results
});
find(str,'l')
Here the working fiddle: http://jsfiddle.net/bx8sj0gv/
The position is two, because there is no loop here, so your search will only hit once, which will only display "2" in this case.
You will need to create and array of chars and loop through it like this:
input_1 = [ "hello", "world" ];
for(var i=0; i<input_1.length; i++){
pos = str.search(/l/g);
out.value = pos;
}
This is merely an example, but it will help you understand the concept of it all.
Try this:
var str="Hello World";
var needle='l';
var temp=[];
for(var i=0; i < str.lengt
if(str[i]===haystack){
temp.push(i)
}
}
console.log(temp);
Your code finds only the first instance of the letter and then returns. You need to list over every character of the string like so:
str = "Hello World"
for (var i = 0, len = str.length; i < len; i++) { if(str[i] == "l")
{ console.log(i );
}
}
Here is a link which done this
Finding all indexes of a specified character within a string
var str = "scissors";
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === "s") indices.push(i);
}
While loop solution:
var indices = function(find, where) {
var arr = [];
for (var i = 0, l = where.length; l > i; i++)
if (find === where[i])
arr.push(i);
return arr;
};
alert(indices("l", "Hello World")); // [2, 3, 9]
Recursive solution:
var indices = function(find, where) {
var i = where.lastIndexOf(find);
if (-1 === i) return [];
return indices(find, where.substr(0, i)).concat([i]);
};
alert(indices("l", "Hello World")); // [2, 3, 9]
Hi I'm trying to split a string based on multiple delimiters.Below is the code
var data="- This, a sample string.";
var delimiters=[" ",".","-",","];
var myArray = new Array();
for(var i=0;i<delimiters.length;i++)
{
if(myArray == ''){
myArray = data.split(delimiters[i])
}
else
{
for(var j=0;j<myArray.length;j++){
var tempArray = myArray[j].split(delimiters[i]);
if(tempArray.length != 1){
myArray.splice(j,1);
var myArray = myArray.concat(tempArray);
}
}
}
}
console.log("info","String split using delimiters is - "+ myArray);
Below is the output that i get
a,sample,string,,,,This,
The output that i should get is
This
a
sample
string
I'm stuck here dont know where i am going wrong.Any help will be much appreciated.
You could pass a regexp into data.split() as described here.
I'm not great with regexp but in this case something like this would work:
var tempArr = [];
myArray = data.split(/,|-| |\./);
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] !== "") {
tempArr.push(myArray[i]);
}
}
myArray = tempArr;
console.log(myArray);
I'm sure there's probably a way to discard empty strings from the array in the regexp without needing a loop but I don't know it - hopefully a helpful start though.
Here you go:
var data = ["- This, a sample string."];
var delimiters=[" ",".","-",","];
for (var i=0; i < delimiters.length; i++) {
var tmpArr = [];
for (var j = 0; j < data.length; j++) {
var parts = data[j].split(delimiters[i]);
for (var k = 0; k < parts.length; k++) {
if (parts[k]) {
tmpArr.push(parts[k]);
}
};
}
data = tmpArr;
}
console.log("info","String split using delimiters is - ", data);
Check for string length > 0 before doing a concat , and not != 1.
Zero length strings are getting appended to your array.
Assume we have a string like the following :
,34,23,4,5,634,23,12,5,4,3,1234,23,54,,,,,,,123,43,2,3,4,5,3424,,,,,,,,123,,,1234,,,,,,,45,,,56
How can we convert it to the following string with RegExp in Javascript ?
34,23,4,5,634,12,3,1234,54,123,43,2,3424,45,56
Actually, I wanna remove repeated items and first and last , char
[edited] To turn these into a set of unique numbers, as you are actually asking for, do this:
function scrapeNumbers(string) {
var seen = {};
var results = [];
string.match(/\d+/g).forEach(function(x) {
if (seen[x]===undefined)
results.push(parseInt(x));
seen[x] = true;
});
return results;
}
Demo:
> scrapeNumbers(',1,22,333,22,,333,4,,,')
[1, 22, 333, 4]
If you had an Array.prototype.unique() primitive, you could write it like so in one line:
yourString.match(/\d+/g).map(parseBase10).unique()
Unfortunately you need to be a bit verbose and define your own parseBase10 = function(n){return parseInt(n)} due to this ridiculous hard-to-track-down bug: javascript - Array#map and parseInt
No need for regex. Few tricks
text = ',34,23,4,5,634,23,12,5,4,3,1234,23,54,,,,,,,123,43,2,3,4,5,3424,,,,,,,,123,,,1234,,,,,,,45,,,56';
text = text.replace(/,+/g, ','); //replace two commas with one comma
text = text.replace(/^\s+|\s+$/g,''); //remove the spaces
textarray = text.split(","); // change them into array
textarray = textarray.filter(function(e){ return e.length});
console.log(textarray);
// Now use a function to make the array unique
Array.prototype.unique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(this[i] in u)
continue;
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
textarray = textarray.unique();
text = textarray.join(','); //combine them back to what you want
console.log(text);
Demo
If you are familier with jQuery
text = text.replace(/,+/g, ',');
text = $.trim(text);
text = $.unique(text.split(",")).filter(function(e){ return e.length}).join(",");
console.log(text);
Demo
This will do it:
function arrIndex(fnd, arr) {
for (var len = arr.length, i = 0; i < len; i++) {
if (i in arr && arr[i] === fnd) {
return i;
}
}
return -1;
}
function scrapeNumbers(str) {
var arr = str.replace(/,+/g, ",").replace(/^,/, "").replace(/,$/, "").split(",");
for (var i = 0, len = arr.length, rtn = []; i < len; i++) {
if (i in arr && arrIndex(arr[i], rtn) == -1) {
rtn.push(arr[i]);
}
}
return rtn.join(",");
}
var str = ",,34,23,4,5,634,23,12,5,4,3,1234,23,54,,,,,,,123,43,2,3,4,5,3424,,,,,,,,123,,,1234,,,,,,,45,,,56,,";
alert(scrapeNumbers(str));
Here is a jsFiddle
Note: I created a custom array.indexOf function for a better browser support
How can I remove a sub-string (a prefix) from a array of string elements? (remove the sub string from each element)
Using RegExp and ^ to ensure it is the prefix and not just somewhere in the string:
var arr = ['a1', 'a2', 'a54a'];
for(var i = 0, len = arr.length; i < len; i++) {
arr[i] = arr[i].replace(/^a/, '');
}
arr; // '1,2,54a' removing the 'a' at the begining
function trimPrefix(str, prefix) {
if (str.startsWith(prefix)) {
return str.slice(prefix.length)
} else {
return str
}
}
var prefix = "DynamicPrefix"
trimPrefix("DynamicPrefix other content", prefix)
Many of the answers already given are wrong, because they'll remove the target string from anywhere in each of the elements (not just the beginning). Here's another approach:
var str = "str_";
["str_one", "str_two_str_", "str_three"].map(function(el) {
return el.replace(new RegExp("^" + str), '');
});
Result:
["one", "two_str_", "three"]
Or, if you prefer simple iteration (with no higher-order function):
var str = "str_";
var list = ["str_one", "str_two_str_", "str_three"];
for (var i = 0; i < list.length; i++)
list[i] = list[i].replace(new RegExp("^" + str), '');
var pre = 'prefix_';
my_arr = my_arr.map(function(v){ return v.slice(pre.length); });
See MDN if full browser support for .map() is needed.
you can also use .forEach() if you need to keep the original array.
var pre = 'prefix_';
my_arr.forEach(function(v,i){ my_arr[i] = v.slice(pre.length); });
var i;
for(i = 0; i < arr.length; i++)
arr[i] = arr[i].replace(substr, '');
Example:
var arr = ['test1', '2test', '3test3'];
// Use only one of these lines
var substr = 'test'; // This is for substrings
var substr = /^test/; // This is for prefixes only
var i;
for(i = 0; i < arr.length; i++)
arr[i] = arr[i].replace(substr, '');
console.log(arr); // Prints ["1", "2", "33"] to console
Just for some variety:
substr = new RegExp('(^|\|)prefix_', 'g');
arr = arr.join('|').replace(substr, '').split('|')
edit - to show how you can limit to just the prefix with the right regexp.
Just iterate on your list of string (with a for loop for example) and use the replace method (details here)
Simply loop through them?
var list = ["foo", "bar", "meh"];
for(var i = 0; i < list.length; i++)
list[i] = list[i].substr(1, 1);
http://jsfiddle.net/DcvE2/1/
You could use the jQuery map function -
var arr = $.map(['a1', 'a2'],function (s) {
return s.replace(/^a/,'');
});
I would do this:
var element = document.getElementsByTagName('p');
for(i in element){
str = element[i].innerHTML;
str = str.replace(/^pre_/,'');
element[i].innerHTML = str;
}