Using replace on string with random number - javascript

I'm trying to replace the values for "min" and "max" price within the following URL string:
var url_full = "http://foo.com/?q=&min=0&max=789"
var url_clean = url_full.replace('&min='+ /\d+/,'');
var url_clean = url_full.replace('&max='+ /\d+/,'');
Struggling to replace the prices.

Replacing min and max values with ''
var url_full = "http://foo.com/?q=&min=0&max=789&hellomin=350"
var url_clean = url_full.replace(/&min=\d+/,'&min=').replace(/&max=\d+/,'&max=')
console.log(url_clean);

> var url = new URL(window.location.href);
> url.searchParams.set('min','100'); window.location.href = url.href;

var url_full = "http://foo.com/?q=&min=0&max=789"
var url_clean = url_full.replace('&min='+ /\d+/,'');
var url_clean = url_full.replace('&max='+ /\d+/,'');
console.log(url_clean);
var regex = /\d+/g;
var string = "http://foo.com/?q=&min=0&max=789";
var matches = string.match(regex); // creates array from matches
for(var s=0;s<matches.length;s++){
console.log(matches[s]);
}
document.write(matches);
Use regex and match for finding digits.

Related

Split a String till a word in javascript

I have to split a string till a word in JavaScript.
var urlCurrent = "www.example.com/web/americas/home";
var siteNames = ["americas","international","europe","asia-pacific","africa-middle-east","russia","india"];
var siteNamesJoin = siteNames.join('|');
var siteUrlCurrent = urlCurrent.split(siteNamesJoin);
Here, I have to split the urlCurrent string using the words in the array. so that at the end I have to get www.example.com/web/americas. I am not getting the regex for that.
You may use
new RegExp("^.*?(?:" + siteNamesJoin + "|$)")
The pattern will look like
^.*?(?:americas|international|europe|asia-pacific|africa-middle-east|russia|india|$)
See the regex graph:
Details
^ - start of string
.*? - any 0 or more chars other than line break chars, as few as possible
(?:americas|international|europe|asia-pacific|africa-middle-east|russia|india|$) - any of the values in between pipes or end of string.
See JS demo:
var urlCurrent = "www.example.com/web/americas/home";
var siteNames = ["americas","international","europe","asia-pacific","africa-middle-east","russia","india"];
var siteNamesJoin = siteNames.join('|');
var match = urlCurrent.match(new RegExp("^.*?(?:" + siteNamesJoin + "|$)"));
var siteUrlCurrent = match ? match[0] : "";
console.log(siteUrlCurrent);
NOTE: if the siteNames "words" may contains special regex metacharacters, you will need to escape the siteNames items:
var siteNamesJoin = siteNames.map(function (x) { return x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') }).join('|');
Also, if those words must match in between / or end of string, you may adjust the pattern:
var match = urlCurrent.match(new RegExp("^(.*?)/(?:(?:" + siteNamesJoin + ")(?![^/])|$)"));
See another demo.
var urlCurrent = "www.example.com/web/americas/home";
var siteNames = ["americas","international","europe","asia-pacific","africa-middle-east","russia","india"];
var siteNamesJoin = siteNames.map(function (x) { return x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') }).join('|');
var match = urlCurrent.match(new RegExp("^.*?/(?:(?:" + siteNamesJoin + ")(?![^/])|$)"));
var siteUrlCurrent = match ? match[0] : "";
console.log(siteUrlCurrent);
using regex & match
var urlCurrent = "www.example.com/web/americas/home";
var siteNames = ["americas","international","europe","asia-pacific","africa-middle-east","russia","india"];
var regex = new RegExp(siteNames.join('|'));
var match = urlCurrent.match(regex);
if(match) {
var url = urlCurrent.substr(0, match[0].length + match.index)
console.log(url);
} else {
//invalid url
}
Maybe this helps you, i guess you don´t need a regex:
var urlCurrent = "www.example.com/web/americas/home";
var siteNames = ["americas","international","europe","asia-pacific","africa-middle-east","russia","india"];
var siteNamesJoin = siteNames.join('|');
var siteUrlCurrent = urlCurrent.split(siteNamesJoin);
const pos = urlCurrent.split("/")[2];
let url;
for(const index in siteNames) {
if(pos === siteNames[index]) {
url = urlCurrent.substring(0,urlCurrent.lastIndexOf("/"));
}
}
console.log(url);

Split url into tab in javascript

input:
"/desh/HRTY/THR/TDR/2015-01-09?passengers=STANDARD:1&returnDate=2015-01-10&max=0&withThac=false"
javascript:
var params = {};
var paramDelim = link.indexOf('?');
var parmeters = link.substring(paramDelim + 1, link.length);
var parts = parmeters.split('[&=]');
output of my js code:
0: "passengers=STANDARD:1&returnDate=2015-01-10&max=0&withThac=false"
length: 1
i want to split my url into a map with key:value like this
output:
origin:THR
destination:TDR
goDate:2015-01-09
passengers:STANDARD:1
returnDate:2015-01-10
max:0
withThac:false
My code not do exactly what i want in output, what is wrong ?
You should split with
var params = parmeters.split('&')
and then split all the values you get
for (var i = 0,len = params.length; i<len;i++){
var data = params[i].split("=", 2); // Max 2 elements
var key = data[0];
var value = data[1];
...
}
i think your wrong ' characters
var params = {};
var paramDelim = link.indexOf('?');
var parmeters = link.substring(paramDelim + 1, link.length);
/*--> i think used regexp. Clear ' Char. --> */var parts = parmeters.split(/[&=]/);
use this like..
good luck
A possible solution using ECMA5 methods and assuming that your string is always the same pattern.
var src = '/desh/HRTY/THR/TDR/2015-01-09?passengers=STANDARD:1&returnDate=2015-01-10&max=0&withThac=false',
slice = src.split(/[\/|?|&]/).slice(3),
data = slice.reduce(function (output, item) {
var split = item.split('=');
output[split.shift()] = split.shift();
return output;
}, {
origin: slice.shift(),
destination: slice.shift(),
goDate: slice.shift()
});
document.body.appendChild(document.createTextNode(JSON.stringify(data)));

Replace dynamic string value in Javascript

I need to replace a dynamic value of a string:
My dynamic value is resulOffset=25
I tried like this:
var str = 'http://example.com?resultLimit=25&resulOffset=25';
var resultOffset = 50;
var newOffset = str.replace(/(resultOffset=)([0-9]+)/, '$1' + resultOffset);
console.log(newOffset);
but doesn't work. How can I solve it?
here: var str = 'http://example.com?resultLimit=25&resulOffset=25';
you have resulOffset instead of resultOffset.
try this one,
var str = 'http://example.com?resultLimit=25&resulOffset={0}';
var resultOffset = 50;
var newOffset = str.replace('{0}',resultOffset);
console.log(newOffset);

How to separate integer value from a string?

I have a string that contains alphabets and integer like banana12,apple123, i wanted to separate integer value from a string. I have used split() function its working perfectly for single digit number ( orange1 ) but for double digit number it is returning only single digit.
myString = banana12;
var splits = myString.split(/(\d)/);
var prodName = splits[0];
var prodId = splits[1];
the prodId should be 12 but its returning only 1 as result.
This will do it-
myString = "banana1212";
var splits = myString.split(/(\d+)/);
var prodName = splits[0];
var prodId = splits[1];
alert(prodId);
http://jsfiddle.net/D8L2J/2/
The result will be in a separate variable as you desired.
You can extract numbers like this:
var myString = "banana12";
var val = /\d+/.exec(myString);
alert(val); // shows '12'
DEMO :http://jsfiddle.net/D8L2J/1/
Try this
var myString = "banana1234";
var splits = myString.split(/(\d{1,})/);
var prodName = splits[0];
var prodId = splits[1];
alert(prodId);
fiddle: http://jsfiddle.net/xYB2P/

How to get a numeric value from a string in javascript?

Can anybody tell me how can i get a numeric value from a string containing integer value and characters?
For example,I want to get 45 from
var str="adsd45";
If your string is ugly like "adsdsd45" you can use regex.
var s = 'adsdsd45';
var result = s.match(/([0-9]+)/g);
['45'] // the result, or empty array if not found
You can use regular expression.
var regexp = /\d+/;
var str = "this is string and 989898";
alert (str.match(regexp));
Try this out,
var xText = "asdasd213123asd";
var xArray = xText.split("");
var xResult ="";
for(var i=0;i< xArray.length - 1; i++)
{
if(! isNan(xArray[i])) { xResult += xArray[i]; }
}
alert(+xResult);
var str = "4039";
var num = parseInt(str, 10);
//or:
var num2 = Number(str);
//or: (when string is empty or haven't any digits return 0 instead NaN)
var num3 = ~~str;
var strWithChars = "abc123def";
var num4 = Number(strWithChars.replace(/[^0-9]/,''));

Categories

Resources