How to create dynamic regex in javascript - javascript

I want to use $htppBackend to mock some service. My problem is some of service url have parameter, ex: http://domain/service1?param1=a&param2=b
I need an regex which can reconize http://domain/service1<whatever> is correct for http://domain/service1?param1=a&param2=b. One thing, the first part http://domain/service1 is not a constant, it can be http://domain/service2/sth/anything.
Please help. Thanks.
Edit:
I put my code here to make it easy to understand.
I have 4 api urls:
angular
.module('moduleName')
.constant('getApi', {
attrList: 'http://domain/setup/attrList',
eventList: 'http://domain/setup/eventList',
vcList: 'http://domain/api/list1',
getRaDetails: 'http://domain/abc/getDetails?raId={0}&bookId={1}'
});
With attrList, eventList and vcList, they are ok with
$httpBackend.whenGET(getApi.attrList).respond(responseObject);
$httpBackend.whenGET(getApi.eventList).respond(responseObject);
$httpBackend.whenGET(getApi.vcList).respond(responseObject);.
But the last one getRaDetails, it doesn't work with
$httpBackend.whenGET(getApi.getRaDetails).respond(responseObject); because raId and bookId have different value each times.
Now I need a regex to make this rule - $httpBackend.whenGET(getApi.getRaDetails).respond(responseObject); works with all raId and bookId value.
Hope it can explain my question more clearly. Thanks

I need an regex which can reconize http://domain/service1 is
correct for http://domain/service1?param1=a&param2=b
I don't think a regex is required here. Just simply check
var stringPattern = "http://domain/service1";
var input = "http://domain/service1?param1=a&param2=b";
if ( input.indexOf( stringPattern ) == 0 )
{
alert( "correct" );
}
else
{
alert( "Incorrect" );
}

So, if you are parsing Urls, it's best to use the URL object in JavaScript:
var input = 'http://domain/abc/getDetails?raId={0}&bookId={1}';
var test = 'http://domain/abc/getDetails';
var testUrl = new URL(test);
var inputUrl = new URL(input);
then test the various bits:
if(testUrl.pathname === inputUrl.pathname){
// they both have /abc/getDetails as the path
}

This's my working code:
_(getApis).each(function (api) {
var val = api.value.split('?')[0].replace(/\//g, '\\/'),
reg = new RegExp(val);
$httpBackend.whenGET(reg).respond(dummy[api.key]);
});
Thanks all.

Related

How to get the first 3 digits from a cell

So I have got a column and i want to get the first 3 digits only from it and store them in a function called wnS using the split function or any other method that would work. I want to get the first three digits before "_"
I tried doing this but it didn't work, and I also kept getting "TypeError: wnC.split is not a function"
var ssh = ssPO.getSheetByName("PO for OR (East).csv")
wnC = ssh.getRange("N2:N");
var wnS = wnC.split("_");
I would really appreciate an answer
If you need more info please let me know
Thank you.
After you define range, you have to get the values.
function first_3_digs (){
var ssh = ssPO.getSheetByName("PO for OR (East).csv")
var wnC = ssh.getRange("N2:N");
var values = wnC.getValues();
const first_3_digs = values.filter(r => {
if(r.toString().includes('_')){return r;}
}).map(r=> r.toString().split('_')[0]);
console.log(first_3_digs)
}
const cell = "(303) 987-4567";
const first3 = cell.match(/\d{3}/)[0];
//result:303
String method match()
regular expression
BTW: you can test methods like this very easily in the console.log in the browsers developer tools.

Javascript that removes part of string / url query parameters

i use the code below to format some links. Where it can add either a suffix or a prefix to the link. But i have been researching how to remove part of the link.
Example, this link below.
https://www.torrid.com/product/boyfriend-straight-jean---vintage-stretch-medium-wash/14478822.html?cgid=Clothing_Jeans_Straight_Boyfriend#promo_id=210802_Jeans&promo_name=BoyfriendStraight_BoyfriendStraight&promo_creative=2107_FG_Denim_Boyfriend_Straight_277x702&promo_position=Jeans_Slide3&start=1
It has superfluous data, everything after
https://www.torrid.com/product/boyfriend-straight-jean---vintage-stretch-medium-wash/14478822.html
Isn't needed, how can i remove everything past that point when formatting the links, before adding the suffix or prefix. Thanks in advance for any help!
$("#btnGenerateLinks").on("click", function() {
var valNeed = $("#strngtime").val();
// if (valNeed.trim().length) { // For filter blank string
$('input[name="linktype1"]').each(function() {
$(this).val($(this).data("link") + valNeed);
});
$('input[name="linktype2"]').each(function() {
$(this).val(valNeed + $(this).data("link"));
});
// }
});
Update - Yes all query parameters
Update - Going with a simple split for now
var myArr = valNeed.split("?")[0];
you can use the URL constructor API
let url = "https://www.torrid.com/product/boyfriend-straight-jean---vintage-stretch-medium-wash/14478822.html?cgid=Clothing_Jeans_Straight_Boyfriend#promo_id=210802_Jeans&promo_name=BoyfriendStraight_BoyfriendStraight&promo_creative=2107_FG_Denim_Boyfriend_Straight_277x702&promo_position=Jeans_Slide3&start=1"
let instance = new URL(url);
let cleanURL = instance.origin + instance.pathname;
console.log(cleanURL);
// https://www.torrid.com/product/boyfriend-straight-jean---vintage-stretch-medium-wash/14478822.html

Input field add symbols

This a function that allows people to type only English characters and numbers in a text field. Basically I need to update this function and allow to type in symbols too. I don't know anything about javascript function and I would appreciate if someone could send me the updated function. I know it might be really easy to do it if I knew how to code 🙃
Is there anyone who can help? Thank you
function add_js_code() {
echo "<script>jQuery('.wc-pao-addon-wrap input[type=\"text\"], .wc-pao-addon-wrap textarea').keyup(function(){
var input_val = jQuery(this).val();
var inputRGEX = /^[a-zA-Z0-9]*$/;
var inputResult = inputRGEX.test(input_val);
if(!(inputResult))
{
this.value = this.value.replace(/[^a-z0-9\s]/gi, '');
}
});</script>";
}
add_action( 'wp_footer', 'add_js_code' );
Replace your regex
FROM
var inputRGEX = /^[a-zA-Z0-9]*$/;
TO
var inputRGEX = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]/;
You can also modify the

How to get a specific portion of the url using javascript?

var url = window.location.href.toString();
the above line gives me the url of my current page correctly and my url is:
http://localhost/xyzCart/products.php?cat_id=35
However, using javascript how can i get only a portion of the url i.e. from the above url i just want
products.php?cat_id=35
How to accomplish this plz help.I have looked at similar questions in this forum but none were any help for me..
You can sliply use this:
var url = window.location.href.toString();
var newString = url.substr(url.lastIndexOf(".") + 1));
This will result in: php?cat_id=35
Good luck /Zorken17
You can use the location of the final /:
var page = url.substr(url.substr(0, (url + "?").indexOf("?")).lastIndexOf("/") + 1);
(This allows for / in a query string)
You can get your desired result by using javascript split() method.check this link for further detail
https://jsfiddle.net/x06ywtvo/
var urls = [
"http://localhost/xyzCart/products.php?cat_id=35",
"http://localhost/xyzCart/products.php",
"http://www.google.com/xyzCart/products.php?cat_id=37"
];
var target = $('#target');
for(var i=0;i<urls.length;i++){
var index = urls[i].indexOf("xyzCart");
var sub = urls[i].substring(index, urls[i].length);
target.append("<div>" + sub + "</div>");
}
Try the folowing javacript code to get the part you need. It splits up your url by the "/"s and takes the fourth part. This is superior to substr solutions in terms of descriptive clarity.
url.split("/")[4]
Or if url can contain more "/" path parts, then simply take the last split part.
var parts = url.split("/");
console.log( parts[parts.length-1] );
You will get all necessary values in window.location object.
Kindly check on following CodePen Link for proper output.
I have added parameter test=1
Link: http://codepen.io/rajesh_dixit/pen/EVebJe?test=1
Code
(function() {
var url = window.location.pathname.split('/');
var index = 1;
document.write("URL: ");
document.write(window.location.href);
document.write("<br/> Full Path: ");
document.write(window.location.pathname);
document.write("<br/> Last Value:")
// For cases where '/' comes at the end
if(!url[url.length - index])
index++;
document.write(url[url.length-index])
document.write("<br/> Query Parameter: ");
document.write(window.location.search.substring(1));
})()

jQuery VAR in IF statement usage

I am sure that this will be a simple solution for someone well versed in jquery.
I am wanting to pass the path name into the if statement so
http://address.com/catalog/product <= catalog then gets passed into the if statment.
if (/\/catalog\//.test(window.location)) {
jQuery('#name-div').hide();
}
so it hides a div if its a child of http://address.com/catalog
var url = location.pathname.split("/")[1];
if (/\/url\//.test(window.location)) {
jQuery('#name-div').hide();
}
As I read your question, what you need is to create a RegExp object from a string since your want to pad with / characters:
var url = location.pathname.split("/")[1],
re = new RegExp('/' + url + '/'); // Create RegExp object from padded string
if (re.test(window.location)) {
jQuery('#name-div').hide();
}
You basically have the answer to your own problem.
$(function(){
var url = window.location.href;
if( /catalog/i.test(url) )
$('#name-div').hide();
});
Unless you have other URLS with catalog in them, there's no reason to dissect the URL any further. Just make sure you select your element after the DOM is ready as I did in my example.
you can do it in many way like:
if( window.location.indexOf(url) !== -1 )
or
if( window.location.search( /url/ig ) )
or
if( window.location.match( /url/ig ).length > 0 )
In this examples you don't even need to use jQuery. It is just normal javascript.

Categories