String IndexOf within a sentance of an array - javascript

I am trying to perform a simple indexOf on my array
the thing is that it just looks for the entire text within my array node
var arr = new Array();
arr.push("hello world");
var result = arr.indexOf("hello");
my problem is that the result I get is -1
is there any way to get the indexOf to search within each of the array element without another loop?
thanks

No, its not possible to use arr.indexOf to search for substring, you have to use loop.
Although you can add method to array to call it to find the substring in array.
Live Demo
Function definition.
arr.containsIndexOf = function(str) {
for(var i = 0; i < arr.length; i++){
if(arr[i].indexOf(str) != -1)
return i;
}
return -1;
}
Function call
arr.containsIndexOf("hello")

Like Adil said you need to use a loop.
var myArr= new Array();
myArr.push("hello world");
function searchArr(txt, arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].toLowerCase().indexOf(txt.toLowerCase()) > -1) {
return i
}
}
}
use this function like this
searchArr("hello",myArr); //returns 0
You might have a array with multiple "hello", so you need to know where all of them are.
myArr.push("hello world")
myArr.push("hello Pluto");
myArr.push("hi sun");
myArr.push("Hello Moon");
function searchArr(txt, arr) {
var arrList = new Array();
for (var i = 0; i < arr.length; i++) {
if (arr[i].toLowerCase().indexOf(txt.toLowerCase()) > -1) {
arrList.push(i);
}
}
return arrList
}
searchArr("hello",myArr); //returns [0, 1, 3]

As #Adil said, No you can't use indexOf function of Array to find substring but you can use indexOf of String to find substring:
Example:
var mystr = 'hello world';
var index = mystr.indexOf('hello');
With your example you should try somethings like:
var arr = new Array();
arr.push("hello world");
var mystr = arr[0]; // this is String object
var index = mystr.indexOf("hello");
Documentation:
string.indexOf
array.indexOf

Try this:
var arr = new Array();
arr.push("hello world");
var result = arr[0].indexOf("hello");
Because this is an Array so you need to access it with it's index.

You're pushing the whole of the string hello world into one index of the array so indexOf will only work when you use as it needs to match the whole item in that array index.
var result = arr.indexOf("hello world");
One way to do it would be like this:
var arr = new Array();
arr.push("hello world");
for(var i = 0; i < arr.length; i++){
if(arr[i].indexOf('hello') != -1)
return i;
}
See this jsfiddle

// Get index of the first matching item in an array
// or -1 if the item is not found
function SearchArray(arr, txt) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].indexOf(txt) > -1) {
return i;
}
}
return -1;
}
Function call:
var someArray = new Array();
someArray.push("hello world");
SearchArray(someArray, "hello");

Related

How to create javascript array when each element is a pair of objects

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;

How to get the positions of an specified char?

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]

splitting a string based on delimiter using javascript

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.

Remove duplicate commas and extra commas at start/end with RegExp in Javascript, and remove duplicate numbers?

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

Remove prefix from a list of strings

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

Categories

Resources