I have a String having URL like:
var url ="http://ispeakphone.com/checkout/cart/add/uenc/aHR0cDovL2lzcGVha3Bob25lLmNvbS9zYW1zdW5nL3NhbXN1bmctZ2FsYXh5LXMvZ2FsYXh5LXM5LXBsdXMuaHRtbA,,/product/619/form_key/foxmD7jgFv31xmEs/qty/3/?options=cart";
I am getting quantity on button click from input as well like:
var qty = jQuery(this).siblings('.quantity-field').val(); // 4
How can I change this qty in URL String "/qty/3/" to "/qty/4/" on every time I get new value from input on button click?
I can't simply find and replace because i don't know /qty/3 exact number its dynamic it could be 2,3,4,5 etc
here is function for having this functionality
function changeValue(str,value){
return str.replace(/\/qty\/[0-9]+\//,`\/qty\/${value}\/`)
}
console.log(url,4);
You can use replace method.
capture everything up to /qty in group 1 (g1), all the following digits in group 2 (g2), and remaining in group 3 (g3), in callback change value of group 2 as required.
var url ="http://ispeakphone.com/checkout/cart/add/uenc/aHR0cDovL2lzcGVha3Bob25lLmNvbS9zYW1zdW5nL3NhbXN1bmctZ2FsYXh5LXMvZ2FsYXh5LXM5LXBsdXMuaHRtbA,,/product/619/form_key/foxmD7jgFv31xmEs/qty/3/?options=cart";
let desired = url.replace(/^(.*\/qty\/)(\d+)(.*)$/g, function(match,g1,g2,g3){
return g1+ (Number(g2)+1) + g3
})
console.log(desired)
Related
I have some tasks to handle in my daily jobs, so I need to do it in a automatic way. My task is:
there will be some messages sent to my IM, and I need to append the first, second & third number to each links with a "|".
if there only 2 numbers in the number line, a 0 is needed in the first place.
For example, in the cleanResult example, I need it to be done like:
finalResult = ["https://www.example.com/firstlink|500",
"https://www.example.com/firstlink|150",
"https://www.example.com/firstlink|30",
"https://www.exmaple.com/secondlink|600",
"https://www.exmaple.com/secondlink|150",
"https://www.exmaple.com/secondlink|30",
"https://www.example.com/thirdlink|500",
"https://www.example.com/thirdlink|150",
"https://www.example.com/thirdlink|30",
"https://www.example.com/forthlink|600",
"https://www.example.com/forthlink|100",
"https://www.example.com/forthlink|20",
"https://www.example.com/fithlink|0",
"https://www.example.com/fithlink|200",
"https://www.example.com/fithlink|50"
]
Here's the codes I had done so far:
const urlRegex = /(https?\:\/\/)?([^\.\s]+)?[^\.\s]+\.[^\s]+/gi;
const digitRegex = /^(?=.*\d)[\d ]+$/;
cleanResult = ["https://www.example.com/firstlink",
"https://www.exmaple.com/secondlink",
"https://www.example.com/thirdlink",
"500 150 30",
"https://www.example.com/forthlink",
"600 100 20",
"https://www.example.com/fithlink",
"200 50"
]
cleanResult.forEach((item, index) => {
if (item.match(digitRegex)) {
//codes I don't know how to do...
}
})
Are elements in cleanResult always either a URL or a number? In that case, you could just check the first character of the string to see if it's a number (basically a non-url). If it's not a URL, then we know it's numbers, and we can do something with the URL, which should the the previous element:
// If it's a URL, we will store it here for future use
let currentURL = ''
cleanResult.forEach((item, index) => {
// Get the first character of this string
const first = item[0]
if (!Number.isInteger(first)) {
// This is NOT a number, so must be a URL,
// let's store it in our variable to use in the next loop
currentURL = item
} else {
// This IS a number, which means we need to do a few things:
// 1. Split into separate numbers
// 2. Create a new URL pattern from each number
// 3. Push to finalResult
// 1. Split by tab delimiter (?)
// splits by tab, and returns an array
const numbers = item.split('\t')
// 2. Create a new URL pattern from each number
numbers.forEach((n) {
// This should now give you the URL + | + the number:
// ex: https://example.com/firstlink|500
const newURL = currentURL + '|' + n
// 3. push to the finalResult array
finalResult.push(newURL)
})
}
})
I haven't tested it, but this is the process that I generally use: break it into smaller tasks and take it one step at a time. I also didn't use regex, just to make it easier. We're assuming that you will receive either a URL or a list of numbers separated by a tab. This means you can afford to keep it a bit simple.
I'm sure there are way more efficient ways to do it and in a lot fewer lines, but if you're just learning JS or programming, there is nothing wrong with being extra verbose so that you can understand early concepts.
I have a scenario like Need to edit the single quotes values (only single quotes values),
So I extracted the single quotes values using regex and prepare the reactive dynamic form.
onclick of performing edit button will show old step name above, new step name below, submit step will replace the step name in the original array.
WOrking fine as expected in few scenarios according to my approach, but in scenarios, I realized whatever algorithm I am following does not fulfill my requirement.
Below are the test cases
Test case 1:
Step Name: "Then I should hire an employee using profile '1' for 'USA'",
// Here --> '1', 'USA' values are editable
Test case 2: "And Employee should be hired on '01' day of pay period '01' of 'Current' Fiscal"
// '01', '01', 'Current'
Issues: in test case 2 if I tried to edit second 01 it is editing the first 01
I try to solve the perform edit function with help of indexof, substring functions
this.replaceString = this.selectedStep.name;
this.metaArray.forEach((element: any) => {
var metaIndex = this.replaceString.indexOf(element.paramValue);
if (metaIndex !== -1) {
const replaceValue = this.stepEditForm.controls[element['paramIndex']].value;
this.replaceString = this.replaceString.substring(0, metaIndex) + replaceValue + this.replaceString.substring(metaIndex + (element.paramValue.length));
}
});
but in indexof always find the first occurrence of a value in a string. So I realized my approach is wrong on performed it function
please find the attachment for the code
https://stackblitz.com/edit/angular-reactive-forms-cqb9hy?file=app%2Fapp.component.ts
So Can anyone please suggest to me how to solve this issue,
Thanks in advance
I added a function called matchStartingPositions that returns the starting position indexes of each match. Using this method you can then perform your edit by replacing the string just as you do, but we'll find the proper match to be replaced at the given position.
So in your line
var metaIndex = this.replaceString.indexOf(element.paramValue);
we can then add a second parameter to indexOf, that is the starting point:
var metaIndex = this.replaceString.indexOf(element.paramValue, startingPositions[element.paramIndex]);
The function for getting the index positions just looks for those single quotes in a given string:
matchStartingPositions(str) {
let count = 0;
let indices = [];
[...str].forEach((val, i) => {
if (val === "'") {
if (count % 2 == 0) {
indices.push(i);
}
count++;
}
});
return indices;
}
Here it is in action:
https://angular-reactive-forms-xhkhmx.stackblitz.io
https://stackblitz.com/edit/angular-reactive-forms-xhkhmx?file=app/app.component.ts
Sometimes in a HTML file, we have a <p> tag that shows the price of a product. For example the price is "1,200,000 Dollar". Now a user added this product to the cart. I want that the webpage display the total price in the cart.
Now in JavaScript I want the program separate the number of price from string and put that in a variable. Here in the example that I said the <p> tag shows "1,200,000 Dollar". Now I want to put just the number(in the example the number is 1,200,000) in a variable to calculate the total price later.
What should I do?
You can also use a split function in this case.
const currencyString="1,000,000 Dollars";
const currencyNumber=Number(currencyString.split(' ')[0].replace(/,/g, ''));
Does the below answer your question...
var input = '1,200,000 Dollar';
var output = Number(input.replace(/[^0-9\-\.]/g, ''));
First we remove all non-digit characters with .replace method and then create a new Number value.
A few other usage examples:
function stringToNumber(string) {
return Number(string.replace(/[^0-9\-\.]/g, ''));
}
var inputs = [
'1,000,000 Dollars',
'$1,000,000.50',
'-50.12 USD'
];
for (var i = 0; i < inputs.length; i++) {
console.log(inputs[i], stringToNumber(inputs[i]));
}
I have a html textarea element in my page where user gives comma separate values. for example below.
A-48402,AA,SBAFL,AA+,USD,,
From javascript (which I prefer) I am applying logic to check if the last row value is blank (separated by comma only) then to put a String value 'Y'. Thus I am writing the below
var data = document.getElementById('txid').value;
rows = data.split('\n');var row1 = rows[0];row1Values=row1 .split(',');
Then I am applying logic to verify whether the last value for every row is blank or not, which is actually blank, then adding the below.
row_values.push('Y');
It is reflecting in debugger.
But what I see is the value 'Y' in the Java action class is not reflecting and showing usual 'Y' while the page submit. How can I add this value 'Y' in every rows end (where there is blank) so that it will be visible in action class?
String Data = request.getParameter('mbs_inst_data');
This data is populated with the same blank values.
If you're only checking for the last row then the only case that would happen is when it's ,,
so you can just do a simple check
let data = 'A-48402,AA,SBAFL,AA+,USD,,'
data = data.split(',')
let lastRowIsBlank = data[data.length-2] === ""
// we are doing length - 2 because in your situation we have 2 ""
// since you have two commas. If you have only 1 comma we would
// the same steps but with length - 1
if(lastRowIsBlank) data[data.length-2] = "Y"
return data.toString()
You can use it like this.
<p id="demo">Visit Microsoft! ,,</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace(/,,$/, ',Y');
document.getElementById("demo").innerHTML = res;
}
</script>
Output
Visit Microsoft! ,Y
I guess this would help you.
This question already has answers here:
How to retrieve GET parameters from JavaScript [duplicate]
(17 answers)
Closed 7 years ago.
I have a URL string in JavaScript below ex-
URL-"/MyProject/Information/EmpDetails.aspx?userId=79874&countryId=875567"
Now, I need to do below 2 things
Check whether the country exists in above url or not and there will be only one countryId in above url
Get the countryId value means 875567.
Thanks Guys for such good response quickly .I got the solution most of the answers are correct.
One More Question Guys I have hyperlink so i am generating some activities when onmousedown event .but the issue is it fires even when i do right click only..but i want the event which fires only on clicking the hyperlink double click or right click and then click
Fetch URL using
window.location.href
And
Split with '?' first, '&' next and '=' so that you can get countryId
OR
directly split with '=' and get last value from array that we get after split
You need to use a combination of indexOf() and substring()
var ind = url.indexOf("countryId");
if (ind != -1){
// value is index of countryid plus length (10)
var countryId = url.substring(ind+10);
}else{
//no countryid
}
How about something like this:
var TheString = "/MyProject/Information/EmpDetails.aspx?userId=79874&countryId=875567";
var TheCountry = parseInt(TheString.split('=').pop(), 10);
And then you just need to test if TheCountry is something with if (TheCountry) { ...}
This of course assumes that the URL query string will always have the country ID at the end.
var url ='/MyProject/Information/EmpDetails.aspx?userId=79874& countryId=875567';
alert((url.match(/countryId/g) || []).length);
alert(url.substring(url.lastIndexOf('=')+1));
you can get the count of the occurrence of any string in first alert and get the countryid value by substring.
This will convert your url query into an object
var data = url.split('?')[url.split('?').length - 1].split('&').reduce(function(prev, curr){
var fieldName = curr.split('=')[0];
var value = curr.split('=').length > 1 ? curr.split('=')[1] : '';
prev[fieldName] = value;
return prev
}, {});
then you can just check the value of data.country to get the value
You may also split the string and see if the countryId exists, as below.
var myString = "/MyProject/Information/EmpDetails.aspx?userId=79874&countryId=875567";
myString = myString.split("countryId="); //["/MyProject/Information/EmpDetails.aspx?userId=79874&", "875567"]
if (myString.length === 2) {
alert (myString.pop());
}