I have array of regex pattern, i want to check the url which matches the regex and use it.
please let me know the best way to do it.
The code i have written is something like this.
var a = ['^\/(.*)\/product_(.*)','(.*)cat_(.*)'];
var result = a.exec("/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346");
Expected:
when i use a.exec it should parse the url "/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346"
and give results.
Iterate over the regexes like this:
var a = ['^\/(.*)\/product_(.*)','(.*)cat_(.*)'];
var result = [];
for (var i = 0; i < a.length; i++) {
result.push(RegExp(a[i]).exec("/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346"));
}
All matches are then stored in result.
result[0] is a array with matches from the regex in a at index 0, result[1] --> a[1], etc. If there are no results from the regex, result[x] will be null.
Instead of pushing the regex result to a array, you could also work on the result directly:
for (var i = 0; i < a.length; i++) {
var currentResult = RegExp(a[i]).exec("/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346");
// Do stuff with currentResult here.
}
You can loop over your regex array:
var a = [/^\/(.*)\/product_(.*)/, /(.*)cat_(.*)/];
var results = [];
for (var i = 0; i < a.length; i++) {
var result = a[i].exec("/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346");
results.push(result);
}
console.log(results);
Related
Let's say I have a variable like this:
const numbers = 1234567654321;
How do I loop through each number here?
I'm so mad I can't find an answer on google for such an easy subject.
Here's what I've been trying to do:
const numbers = 1234567654321;
const str = numbers.toString();
let results = [];
for (let i = 0; i <= str.length; i++) {
results.push(+str[i]);
}
console.log(results);
Your code works correctly. There's only one problem which is the loop condition which should be i < str.length
const numbers = 1234567654321;
const str = numbers.toString();
let results = [];
for (let i = 0; i < str.length; i++) {
results.push(+str[i]);
}
console.log(results)
Your own answer seems to work (except for the wrong index, like mentioned by Rifat Bin Reza).
You could also use split() instead of the for-loop:
const numbers = 1234567890;
const result = numbers.toString().split('').map(num => parseInt(num));
console.log(result);
Your code is fine, except for cheking condition i<= str.length should be i < str.length.
Another approach using map().
const number = 12345;
const solution = [...`${number}`].map(number => +number);
console.log(solution);
I want to write a reverse array function and I met the problem. The compiler said my input and my output is the same.
Why did this happen?
Requirement:
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
Here is my JS:
var reverseString = function(str) {
var nowArray = [];
nowArray.push(str);
var newArray = [];
for(let i=nowArray.length-1, k=0; i>=0; i--, k++) {
newArray[k] = nowArray[nowArray.length-1];
nowArray.length--;
}
console.log(newArray);
};
reverseString( ["h","e","l","l","o"]) // Should return["o","l","l","e","h"]
You donot need to push() str in nowArray. This will make it like this
[["h","e","l","l","o"]]
You can directly set it to nowArray
var reverseString = function(str){
var nowArray=str;
var newArray=[];
for(let i=nowArray.length-1,k=0;i>=0;i--,k++){
newArray[k]=nowArray[nowArray.length-1];
nowArray.length--;
}
console.log(newArray);
};
reverseString( ["h","e","l","l","o"])//Should return["o","l","l","e","h"]
Use the following in leetcode
var reverseString = function(s) {
for(let i = 0;i<Math.floor(s.length/2);i++){
let temp = s[i];
s[i] = s[s.length - 1 - i]
s[s.length - 1 - i] = temp;
}
};
I'm guessing you need the answer as an array, hence the forced string to array.
You could make the code simpler:
var reverseString = function(str){
var newStr = [];
for(var i in str) {
newStr.unshift(str[i]);
}
return newStr;
};
You're pushing the entire string to the nowArray instead of the individual characters. Instead just do var nowArray = str.split("") to get an array of characters.
var reverseString = function(str) {
var nowArray = str.split("");
var newArray = [];
for (let i = nowArray.length - 1, k = 0; i >= 0; i--, k++) {
newArray[k] = nowArray[nowArray.length - 1];
nowArray.length--;
}
console.log(newArray);
};
reverseString("hello");
Also, you were passing an array of characters instead of a string to the reverseString function.
Additionally, since you're splitting the string into the nowArray, you can eliminate the second array, and just use that one. This also lets you cut the iterations in half.
var reverseString = function(str) {
var nowArray = str.split("");
for (let i = nowArray.length - 1, k = 0; i > k; i--, k++) {
[nowArray[i], nowArray[k]] = [nowArray[k], nowArray[i]];
}
console.log(nowArray);
};
reverseString("hello");
Jacky, you can also modify the array in place without taking up additional memory. This takes the original string and swaps the values of the two endpoints. Make sure that you quit the loop at str.length/2 otherwise you will get the exact same array. Furthermore, since you are changing the original input, you do not need to return anything since js passes the arguments by reference.
var reverseString = function(str){
for(let i = 0; i < str.length/2; i++){
// you can swap like this ES6
[str[i],str[str.length-i-1]] = [str[str.length-i-1],str[i]];
// or like this
//var tmp = str[i];
//str[i] = str[str.length-i-1]];
//str[str.length-i-1]] = tmp;
}
console.log(str);
};
reverseString( ["h","e","l","l","o"])//Should return["o","l","l","e","h"]
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.
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");
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;
}