Cut string url in javascript - javascript

I have a string like below
var indicator = -65(www.anyweb.com)
the number -65 can be any number too. How can I take out only the web url separately in javascript?

You need to extract the string after '(' and before ')'
var str = "-65(www.anyweb.com)";
str = str.substring(str.lastIndexOf("(")+1,str.lastIndexOf(")"));

You can use this example for string operations
var data = "-65(www.anyweb.com)";
var url = data.slice(data.indexOf('(')+1 ,data.indexOf(')')); console.log("URL :: ",url);

var domain = /\((.*?)\)/.exec("-65(www.anyweb.com)")[1];
console.log(domain);
The regex above will create a group with anything that's inside parenthesis.

You can use some simple string operations:
var str = "-65(www.anyweb.com)";
var url = "N/A";
// Find indices of open and close parentheses
var open = str.indexOf("(");
var close = str.lastIndexOf(")");
// If they were found then extract the URL from the string
if (open !== -1 && close !== -1) {
url = str.substring(open + 1, close);
}
console.log(url);
If you are more inclined to use regular expressions then this should do it:
var str = "-65(www.anyweb.com)";
var regex = /\((.*?)\)/; // Capture URL inside parentheses
var result = regex.exec(str); // Execute the regex against the string
var url = "N/A";
// If the URL was matched then assign it to the variable
if (result[1] !== undefined) {
url = result[1];
}
console.log(url);
You can also simply replace the stuff that you do not want:
var str = "-65(www.anyweb.com)";
str = str.replace(/^.*\(/, ""); // Remove everything before URL
str = str.replace(/\).*$/, ""); // Remove everything after URL
console.log(str);

Example 1 :
var data = "-65(www.anyweb.com)";
if(data.indexOf('(')!=-1){
var url = data.slice(data.indexOf('(')+1 ,data.indexOf(')'));
}
console.log("URL :: ",url);
Example 2 :
var data = "-65";
if(data.indexOf('(')!=-1){
var url = data.slice(data.indexOf('(')+1 ,data.indexOf(')'));
}
console.log("URL :: ",url);
Example 3 :
var data = "-65(www.anyweb.com)6764872";
if(data.indexOf('(')!=-1){
var url = data.slice(data.indexOf('(')+1 ,data.indexOf(')'));
}
console.log("URL :: ",url);

Related

keep string between two words node js express javascript

I have a string like:
var str = put returns between paragraphs abc_start indent code by 4 spaces abc_end quote by placing > at start of line abc_start to make links abc_end.
I'm displaying this string in my browser using:
res.send('/page/+result);
I want to filter out result such that only the content which starts at abc_start and end at abc_end remains. How do I do that in node.js?
For eg: output:
abc_start indent code by 4 spaces abc_end abc_start to make links abc_end
I tried using : str.split('abc_start').pop().split('abc_end').shift();
But I'm not gettting desired output.Please help.
<script>
function myFunction() {
var str = "abc_start indent code by 4 spaces abc_end";
var n = str.indexOf("abc_start ");
var m = str.indexOf("abc_end");
var res = str.slice(n+9, m-1);//Since you already know the length of the string "abc_start" that you want out of the way
document.getElementById("demo").innerHTML = res;
}
</script>
Below is code snippet to solve this scenario:
var str = 'xxxadasyyydsdsxxxadadyyy';
var start = 'xxx';
var end = 'yyy'
var res = [];
find();
function find() {
var initialIndex = str.indexOf(start);
var lastIndex = str.indexOf(end);
if(initialIndex > -1 && lastIndex > -1 && initialIndex < lastIndex) {
res.push(str.substring(initialIndex, lastIndex + start.length));
str = str.substring(lastIndex + start.length);
find();
} else {
return;
}
}
console.log(res);

Javascript regex match number after string

I have this string
/results?radius=4000&newFilter=true
and I need to replace radius=4000 with radius=n where n is a variable.
How can I use String.replace() method with regex to match that part?
You can use /radius=\d+/ to match "radius=" followed by any number of digits. With this we can use the replace() method to replace it with the desired value:
var str = "/results?radius=4000&newFilter=true";
var replacement = 123;
var newStr = str.replace(/radius=\d+/, "radius=" + replacement);
console.log(newStr);
If you want to get all parameters you can try this :
function getParams(uri) {
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(uri)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}
var str='/results?radius=4000&newFilter=true';
str = str.substring(str.indexOf("?"));
params = getParams(str);
console.log(params);
console.log('radius => ', params['radius']);
This answer is from this post: How to get the value from the GET parameters?
It should be as easy as
var str='/results?radius=4000&newFilter=true';
var n = 1234;
str = str.replace(/(radius=)(\d+)/, "$1" + n);
var url = "/results?radius=4000&newFilter=true";
// or window.location.href for current url
var captured = /radius=([^&]+)/.exec(url)[1]; // your 4000
var newValue = 5000;
url = url.replace(captured, newValue);
by this way you can use it to get all your requested parameters too
and it is not decimal binded
ES6 with regex using positive lookbehind
const string = '/results?radius=4000&newFilter=true',
n = '1234',
changeRadius = (radius) => string.replace(/(?<=radius=)\d+/, n);
console.log(changeRadius(n));
/* Output console formatting */
.as-console-wrapper { top: 0; }
changeRadius is function that takes one parameter (radius) and performs replacement.
About the regex: \d+ gets as many digits as possible, (?<=STRING) is a positive lookbehind.
Other regex
Body of changeRadius() function can be replaced with string.replace(/radius=\d+/, 'radius=' + n). It probably has better performance, but original regex is more direct translation of the problem.
You can use capturing without remembering the match to capture only the numerical value after 'radius='.
var url = "/results?radius=4000&newFilter=true";
var radius = 123;
var newUrl = url.replace(/(?:radius=){1}(\d+)/, radius);
console.log(newUrl); // logs '/results?radius=4000&newFilter=true'0
'

Regex to get last word in URL between / and /

How do I get the last word in a URL that is URL between / and / ?
For example:
http://mywebsite.com/extractMe/test
http://mywebsite.com/extractMe
http://mywebsite.com/settings/extractMe/test
http://mywebsite.com/settings/extractMe
Here I would want to get extractMe from the URL.
If the URL is consistent, why not just use:
// Option 1
var url = "http://mywebsite.com/extractMe/test";
var extractedText = url.split("/")[3];
​// Option 2
// If when a trailing slash is present you want to return "test", use this code
var url = "http://mywebsite.com/extractMe/test/";
var urlAry = url.split("/");
var extractedText = urlAry[urlAry.length - 2];
​// Option 3
// If when a trailing slash is present you want to return "extractMe", use this:
var url = "http://mywebsite.com/extractMe/test/";
var urlAry = url.split("/");
var positionModifier = (url.charAt(url.length-1) == "/") ? 3 : 2;
var extractedText = urlAry[urlAry.length - positionModifier];
Here's a working fiddle: http://jsfiddle.net/JamesHill/Arj9B/
it works with / or without it in the end :)
var url = "http://mywebsite.com/extractMe/test/";
var m = url.match(/\/([^\/]+)[\/]?$/);
console.log(m[1]);
output:
test
This accounts BOTH for URLS like http://mywebsite.com/extractMe/test and http://mywebsite.com/extractMe/
function processUrl(url)
{
var tk = url.split('/');
var n = tk.length;
return tk[n-2];
}
Edited.
Regular Expression way:
var str = "http://example.com/extractMe/test";
var match = str.match(/\/([^\/]+)\/[^\/]+$/);
if (match) {
console.log(match[1]);
}

Looking for a regex to parse parameters string for JS

I cannot find out the regex to get param value from the part of query string:
I need to send parameter name to a method and get parameter value as result for string like
"p=1&qp=10".
I came up with the following:
function getParamValue(name) {
var regex_str = "[&]" + name + "=([^&]*)";
var regex = new RegExp(regex_str);
var results = regex.exec(my_query_string);
// check if result found and return results[1]
}
My regex_str now doesn't work if name = 'p'. if I change regex_str to
var regex_str = name + "=([^&]*)";
it can return value of param 'qp' for param name = 'p'
Can you help me with regex to search the beginning of param name from right after '&' OR from the beginning of a string?
This might work, depending on if you have separated the parameter part.
var regex_str = "(?:^|\&)" + name + "=([^&]*)";
or
var regex_str = "(?:\&|\?)" + name + "=([^&]*)";
Looks like split will work better here:
var paramsMap = {};
var params = string.split("&");
for (var i = 0; i < params.length; ++i) {
var keyValue = params[i].split("=", 2);
paramsMap[keyValue[0]] = keyValue[1];
}
If you desperately want to use a regex, you need to use the g flag and the exec method. Something along the lines of
var regex = /([^=]+)=([^&]+)&?/g;
var paramsMap = {};
while (true) {
var match = regex.exec(input);
if (!match)
break;
paramsMap[match[1]] = match[2];
}
Please note that since the regex object becomes stateful, you either need to reset its lastIndex property before running another extraction loop or use a new RegExp instance.
Change your regex string to the following:
//pass the query string and the name of the parameter's value you want to retrieve
function getParamValue(my_query_string , name)
{
var regex_str = "(?:^|\&)" + name + "\=([^&]*)";
var regex = new RegExp(regex_str);
var results = regex.exec(my_query_string);
try
{
if(results[1] != '')
{
return results[1];
}
}
catch(err){};
return false;
}

Replace part of a string in JavaScript

How can I replace:
var url = "http://localhost:2879/ServiceDonneesArchive.svc/Installations(1002)?$expand=Stations";
by:
var nameInstallation = 1002;
var url = "http://localhost:2879/ServiceDonneesArchive.svc/Installations(nameInstallation)?$expand=Stations";
Why do this the hard way? For this use case, simple concatenation would be very readable:
var nameInstallation = 1002;
var url = 'http://localhost:2879/ServiceDonneesArchive.svc/Installations(' + nameInstallation + ')?$expand=Stations';
Use the .replace() method. To replace any instances of "nameInstallation" in your url variable with "1002":
url = url.replace(/nameInstallation/g, "1002");
Or if you have the replacement value in a variable nameInstallation = 1002:
url = url.replace(/nameInstallation/g, nameInstallation);
EDIT: As pointed out by David Thomas, you probably don't need the g flag on the regular expression that is the first parameter to .replace(). With this "global" flag it will replace all instances of the text "nameInstallation". Without the flag it would replace only the first instance. So either include it or leave it off according to your needs. (If you only need to replace the first occurrence you also have the option of passing a string as the first parameter rather than a regex.)
Try it out this javascript function
// from http://www.codeproject.com/Tips/201899/String-Format-in-JavaScript
String.prototype.format = function (args) {
var str = this;
return str.replace(String.prototype.format.regex, function(item) {
var intVal = parseInt(item.substring(1, item.length - 1));
var replace;
if (intVal >= 0) {
replace = args[intVal];
} else if (intVal === -1) {
replace = "{";
} else if (intVal === -2) {
replace = "}";
} else {
replace = "";
}
return replace;
});
};
String.prototype.format.regex = new RegExp("{-?[0-9]+}", "g");
and use:
var url = "http://localhost:2879/ServiceDonneesArchive.svc/Installations{0}?$expand=Stations";
var nameInstallation = 1002;
var result = url.format(nameInstallation );

Categories