Get substring from between two identical characters in a URL - javascript

How would I extract just the number from between the two slashes in this URL:
https://myDomain.sharepoint.com/sites/MySite/SitePages/MyPage.aspx?/id=612/&CT=1223336827303&OR=OWA-NT&CID=7f71df69-6cef-fd22-82d9-5823a32895f9
I only want the number (612 in this case but can be different no. and can vary in length) and nothing else.
The code I've attempted:
if(window.location.href.indexOf("id=") > -1){
var url = window.location.href;
console.log(url, 'url');
var findUrl = window.location.search;
console.log(findUrl, 'findUrl');
var url2 = url.substring(url.indexOf("=") + 1);
console.log(url2, 'url2');
var url3 = url.substring(
url.lastIndexOf("/") + 1,
url.lastIndexOf("/")
);
var url4 = url.split('/').pop().split('/')[0];
console.log(url3, 'url3');
console.log(url4, 'url4');
this.setState({
Id: url4,
filterValue: url4
}, () => {
this._editItemUrl();
});
}
I've read:
How do you use a variable in a regular expression?
JavaScript - Use variable in string match
get string between two strings with javascript
Buy none answer my specific question.

your problem is the forward slashes in the query-parameter string. If you can remove those (str replace) you can use JS's URLSearchParams.
see: https://www.sitepoint.com/get-url-parameters-with-javascript/

Related

Regex not working to remove string/whatever

How can I remove this string from href and update it ?
Example Url:
"localhost:21088/WcfDataService1.svc/Clients?$top=20&$select=Name,Products/Name,ID,People/FirstName,Products/Price,People/LastName&$expand=People"
What I am trying:
var stringToRemove = "Products" + "/";
var url = $("#qUrl").attr("href");
url = url.replace('/(' + stringToRemove + '\/\w+,)/g', '');
$("#qUrl").attr("href", url);
What I want:
"localhost:21088/WcfDataService1.svc/Clients?$top=20&$select=Name,ID,People/FirstName,People/LastName&$expand=People"
Update
Please don't hard code
If you are looking to remove all Products/..., than RegEx is /Products\/.*?,/g
Take a note that RegExp is written as is - without surrounding it with quotes.
var str = 'localhost:21088/WcfDataService1.svc/Clients?$top=20&$select=Name,Products/Name,ID,People/FirstName,Products/Price,People/LastName&$expand=People';
console.log(str.replace(/Products\/\w+,?/g, ''));
/**
* Replace with variable string
*/
var key = 'Products'; // Come from external source, not hardcoded.
var pattern = new RegExp(key+'/\\w+,?', 'g'); // Without start and end delimiters!
console.log(str.replace(pattern, ''));
var stringToRemove = "Products" + "/";
var url = $("#qUrl").attr("href");
url = url.replace(/Products\/Name,/g, '');
$("#qUrl").attr("href", url);
Modify the replace call , use regex without quotes

How do I replace the port number in JavaScript?

I have an array of strings, and I want to create a new array which contains the same strings without port numbers (the port number is a ":" followed by a number). For example if the string is "http://www.example.com:8080/hello/" Then it should be replaced with "http://www.example.com/hello/". How do I do it in JavaScript? I need it to call safari.extension.addContentScriptFromURL because the whitelist can't contain port numbers. If possible, it's better to replace the port number only between the second and third slash and leave the rest of the string unchanged.
You don't need any library or REGEX
https://developer.mozilla.org/en-US/docs/Web/API/URL
var url = new URL('http://localhost:8080');
url.port = '';
console.log(url.toString());
Regrards
One quite nifty way to do this, is to create an a element, and assign the URL you have as href - because the HTMLAnchorElement interface implements URLUtils, and therefor supports accessing the individual parts of the address in the same way the location object does, and you can set them individually as well:
var foo = document.createElement("a");
foo.href = "http://www.example.com:8080/hello/";
foo.port = ""
var newURL = foo.href;
console.log(newURL); // output: http://www.example.com/hello/
http://jsfiddle.net/pdymeb5d/
This should probably do what you want:
var newUrls = urls.map(function (url) {
return url.replace(/([a-zA-Z+.\-]+):\/\/([^\/]+):([0-9]+)\//, "$1://$2/");
});
Edit: It seems the schema part of URIs can contain "+", "." and "-" also. Changed the regular expression accordingly.
See: https://en.wikipedia.org/wiki/URI_scheme
You can use regex with string.replace() as follows,
var text = "http://www.example.com:8080/hello/";
var withNoDigits = text.replace(/[0-9]/g, '');
var outputString = withNoDigits.replace(/:([^:]*)$/,'$1');
alert(outputString);
function parseURL(url) {
var parser = document.createElement('a'),
searchObject = {},
queries, split, i;
parser.href = url;
queries = parser.search.replace(/^?/, '').split('&');
for( i = 0; i < queries.length; i++ ) {
split = queries[i].split('=');
searchObject[split[0]] = split[1];
}
return {
protocol: parser.protocol,
host: parser.host,
hostname: parser.hostname,
port: parser.port,
pathname: parser.pathname,
search: parser.search,
searchObject: searchObject,
hash: parser.hash
};
}
Use this to parse any URL and arrange in a format you prefer.
OK, I used your answer and changed it a little, because the protocol may contain dashes too:
var newUrls = urls.map(function(url) {
return url.replace(/([^\/\:]+):\/\/([^\/]+):([0-9]+)\//, "$1://$2/");
})
I have found best solution here.
var url = 'http://localhost:7001/www.facebook.com';
// Create a regex to match protocol, domain, and host
var matchProtocolDomainHost = /^.*\/\/[^\/]+:?[0-9]?\//i;
// Replace protocol, domain and host from url, assign tomyNewUrl
var myNewUrl = url.replace(matchProtocolDomainHost, '');
Now myNewUrl === 'www.facebook.com'.
Better to read full page.
remove hostname and port from url using regular expression

How can we split a string using starts with regular expression (/^myString/g)

I am having a case where i need to split given string using starts with regex (/^'searchString'/) which is not working such as
"token=123412acascasdaASDFADS".split('token=')
Here i want to extract the token value but as there might be some other possible parameters such as
"reset_token=SDFDFdsf12313ADADF".split('token=')
Here it also split the string with 'token=', Thats why i need to split the string using some regex which states that split the string where it starts with given string.
Thanks..
EDITED
Guys thanks for your valuable response this issue can be resolve using /\btoken=/ BUT BUT its does not work if 'token=' stored as a string into a variable such as
sParam = 'token=';
"token=123412acascasdaASDFADS".split(/\bsParam/);
This does not works.
You can use regex in split with word boundary:
"token=123412acascasdaASDFADS".split(/\btoken=/)
If token is stored in a variable then use RegExp constructor:
var sParam = "token";
var re = new RegExp("\\b" + sParam + "=");
Then use it:
var tokens = "token=123412acascasdaASDFADS".split( re );
This is the use case for the \b anchor:
\btoken=
It ensures there's no other word character before token (a word character being [a-zA-Z0-9_])
You need to split the string using the & parameter delimiter, then loop through those parameters:
var token;
$.each(params.split('&'), function() {
var parval = this.split('=');
if (parval[0] == "token") {
token = parval[1];
return false; // end the $.each loop
}
});
if you just use token= as the split delimiter, you'll include all the other parameters after it in the value.
It's not clear what you need, but this may be an idea to work with?
var reqstr = "token=12345&reset_token=SDFDFdsf12313ADADF&someval=foo"
.split(/[&=]/)
,req = [];
reqstr.map( function (v, i) {
if (i%2==0) {
var o = {};
o[/token/i.test(v) ? 'token' : v] = reqstr[i+1];
this.push(o);
} return v
}, req);
/* => req now contains:
[ { token: '12345' },
{ token: 'SDFDFdsf12313ADADF' },
{ someval: 'foo' } ]
*/
You can try with String#match() function and get the matched group from index 1
sample code
var re = /^token=(.*)$/;
var str = 'token=123412acascasdaASDFADS';
console.log('token=123412acascasdaASDFADS'.match('/^token=(.*)$/')[1]);
output:
123412acascasdaASDFADS
If token is dynamic then use RegExp
var token='token=';
var re = new RegExp("^"+token+"(.*)$");
var str = 'token=123412acascasdaASDFADS';
console.log(str.match(re)[1]);
Learn more...

javascript/jquery add trailing slash to url (if not present)

I'm making a small web app in which a user enters a server URL from which it pulls a load of data with an AJAX request.
Since the user has to enter the URL manually, people generally forget the trailing slash, even though it's required (as some data is appended to the url entered). I need a way to check if the slash is present, and if not, add it.
This seems like a problem that jQuery would have a one-liner for, does anyone know how to do this or should I write a JS function for it?
var lastChar = url.substr(-1); // Selects the last character
if (lastChar != '/') { // If the last character is not a slash
url = url + '/'; // Append a slash to it.
}
The temporary variable name can be omitted, and directly embedded in the assertion:
if (url.substr(-1) != '/') url += '/';
Since the goal is changing the url with a one-liner, the following solution can also be used:
url = url.replace(/\/?$/, '/');
If the trailing slash exists, it is replaced with /.
If the trailing slash does not exist, a / is appended to the end (to be exact: The trailing anchor is replaced with /).
url += url.endsWith("/") ? "" : "/"
I added to the regex solution to accommodate query strings:
http://jsfiddle.net/hRheW/8/
url.replace(/\/?(\?|#|$)/, '/$1')
This works as well:
url = url.replace(/\/$|$/, '/');
Example:
let urlWithoutSlash = 'https://www.example.com/path';
urlWithoutSlash = urlWithoutSlash.replace(/\/$|$/, '/');
console.log(urlWithoutSlash);
let urlWithSlash = 'https://www.example.com/path/';
urlWithSlash = urlWithSlash.replace(/\/$|$/, '/');
console.log(urlWithSlash);
Output:
https://www.example.com/path/
https://www.example.com/path/
It replaces either the trailing slash or no trailing slash with a trailing slash. So if the slash is present, it replaces it with one (essentially leaving it there); if one is not present, it adds the trailing slash.
You can do something like:
var url = 'http://stackoverflow.com';
if (!url.match(/\/$/)) {
url += '/';
}
Here's the proof: http://jsfiddle.net/matthewbj/FyLnH/
The URL class is pretty awesome - it helps us change the path and takes care of query parameters and fragment identifiers
function addTrailingSlash(u) {
const url = new URL(u);
url.pathname += url.pathname.endsWith("/") ? "" : "/";
return url.toString();
}
addTrailingSlash('http://example.com/slug?page=2');
// result: "http://example.com/slug/?page=2"
You can read more about URL on MDN
Before finding this question and it's answers I created my own approach. I post it here as I don't see something similar.
function addSlashToUrl() {
//If there is no trailing shash after the path in the url add it
if (window.location.pathname.endsWith('/') === false) {
var url = window.location.protocol + '//' +
window.location.host +
window.location.pathname + '/' +
window.location.search;
window.history.replaceState(null, document.title, url);
}
}
Not every URL can be completed with slash at the end. There are at least several conditions that do not allow one:
String after last existing slash is something like index.html.
There are parameters: /page?foo=1&bar=2.
There is link to fragment: /page#tomato.
I have written a function for adding slash if none of the above cases are present. There are also two additional functions for checking the possibility of adding slash and for breaking URL into parts. Last one is not mine, I've given a link to the original one.
const SLASH = '/';
function appendSlashToUrlIfIsPossible(url) {
var resultingUrl = url;
var slashAppendingPossible = slashAppendingIsPossible(url);
if (slashAppendingPossible) {
resultingUrl += SLASH;
}
return resultingUrl;
}
function slashAppendingIsPossible(url) {
// Slash is possible to add to the end of url in following cases:
// - There is no slash standing as last symbol of URL.
// - There is no file extension (or there is no dot inside part called file name).
// - There are no parameters (even empty ones — single ? at the end of URL).
// - There is no link to a fragment (even empty one — single # mark at the end of URL).
var slashAppendingPossible = false;
var parsedUrl = parseUrl(url);
// Checking for slash absence.
var path = parsedUrl.path;
var lastCharacterInPath = path.substr(-1);
var noSlashInPathEnd = lastCharacterInPath !== SLASH;
// Check for extension absence.
const FILE_EXTENSION_REGEXP = /\.[^.]*$/;
var noFileExtension = !FILE_EXTENSION_REGEXP.test(parsedUrl.file);
// Check for parameters absence.
var noParameters = parsedUrl.query.length === 0;
// Check for link to fragment absence.
var noLinkToFragment = parsedUrl.hash.length === 0;
// All checks above cannot guarantee that there is no '?' or '#' symbol at the end of URL.
// It is required to be checked manually.
var NO_SLASH_HASH_OR_QUESTION_MARK_AT_STRING_END_REGEXP = /[^\/#?]$/;
var noStopCharactersAtTheEndOfRelativePath = NO_SLASH_HASH_OR_QUESTION_MARK_AT_STRING_END_REGEXP.test(parsedUrl.relative);
slashAppendingPossible = noSlashInPathEnd && noFileExtension && noParameters && noLinkToFragment && noStopCharactersAtTheEndOfRelativePath;
return slashAppendingPossible;
}
// parseUrl function is based on following one:
// http://james.padolsey.com/javascript/parsing-urls-with-the-dom/.
function parseUrl(url) {
var a = document.createElement('a');
a.href = url;
const DEFAULT_STRING = '';
var getParametersAndValues = function (a) {
var parametersAndValues = {};
const QUESTION_MARK_IN_STRING_START_REGEXP = /^\?/;
const PARAMETERS_DELIMITER = '&';
const PARAMETER_VALUE_DELIMITER = '=';
var parametersAndValuesStrings = a.search.replace(QUESTION_MARK_IN_STRING_START_REGEXP, DEFAULT_STRING).split(PARAMETERS_DELIMITER);
var parametersAmount = parametersAndValuesStrings.length;
for (let index = 0; index < parametersAmount; index++) {
if (!parametersAndValuesStrings[index]) {
continue;
}
let parameterAndValue = parametersAndValuesStrings[index].split(PARAMETER_VALUE_DELIMITER);
let parameter = parameterAndValue[0];
let value = parameterAndValue[1];
parametersAndValues[parameter] = value;
}
return parametersAndValues;
};
const PROTOCOL_DELIMITER = ':';
const SYMBOLS_AFTER_LAST_SLASH_AT_STRING_END_REGEXP = /\/([^\/?#]+)$/i;
// Stub for the case when regexp match method returns null.
const REGEXP_MATCH_STUB = [null, DEFAULT_STRING];
const URL_FRAGMENT_MARK = '#';
const NOT_SLASH_AT_STRING_START_REGEXP = /^([^\/])/;
// Replace methods uses '$1' to place first capturing group.
// In NOT_SLASH_AT_STRING_START_REGEXP regular expression that is the first
// symbol in case something else, but not '/' has taken first position.
const ORIGINAL_STRING_PREPENDED_BY_SLASH = '/$1';
const URL_RELATIVE_PART_REGEXP = /tps?:\/\/[^\/]+(.+)/;
const SLASH_AT_STRING_START_REGEXP = /^\//;
const PATH_SEGMENTS_DELIMITER = '/';
return {
source: url,
protocol: a.protocol.replace(PROTOCOL_DELIMITER, DEFAULT_STRING),
host: a.hostname,
port: a.port,
query: a.search,
parameters: getParametersAndValues(a),
file: (a.pathname.match(SYMBOLS_AFTER_LAST_SLASH_AT_STRING_END_REGEXP) || REGEXP_MATCH_STUB)[1],
hash: a.hash.replace(URL_FRAGMENT_MARK, DEFAULT_STRING),
path: a.pathname.replace(NOT_SLASH_AT_STRING_START_REGEXP, ORIGINAL_STRING_PREPENDED_BY_SLASH),
relative: (a.href.match(URL_RELATIVE_PART_REGEXP) || REGEXP_MATCH_STUB)[1],
segments: a.pathname.replace(SLASH_AT_STRING_START_REGEXP, DEFAULT_STRING).split(PATH_SEGMENTS_DELIMITER)
};
}
There might also be several cases when adding slash is not possible. If you know some, please comment my answer.
For those who use different inputs: like http://example.com or http://example.com/eee. It should not add a trailling slash in the second case.
There is the serialization option using .href which will add trailing slash only after the domain (host).
In NodeJs,
You would use the url module like this:
const url = require ('url');
let jojo = url.parse('http://google.com')
console.log(jojo);
In pure JS, you would use
var url = document.getElementsByTagName('a')[0];
var myURL = "http://stackoverflow.com";
console.log(myURL.href);

Regex for parsing parameters from url

I'm a total noob with regexes and although I was trying hard I cannot create proper regexes to perform the following operation :
take url and check if it has a '?' followed by number with varying amount of digits.
if the match is correct, get the number after the '?' sign
exchange this number with different one.
So let's say we have this url :
http://website.com/avatars/avatar.png?56
we take '56' and change it to '57'.
I have the following regex for searching, I'm not sure if it's proper :
\?[0-9]+
But I have no idea how to take ? away. Should I just throw it away from the string and forget about using regex here ? Then the replace part is the only one left.
Try this:
var url = "http://website.com/avatars/avatar.png?56";
var match = url.match(/\?(\d+)/);
if(match != null) {
url = url.replace(match[1], "new number");
}
Your original regex will work just fine, just add back in the ? you are taking out like so:
var newnum = 57;
url = url.replace(/\?[0-9]+/, '?'+ newnum);
I'm no regex expert but I think you can use a lookaround to ignore the '?'
(?<=?)([0-9]+)
which should give you your number in the first match
VERY dummied-down approach:
$('#parse').click(function(e){
var fromUrl = $('#from-url').val();
var newNum = parseInt($('#new-number').val(), 10);
var urlRE = /(?!\?)(\d+)$/;
if (urlRE.test(fromUrl)){
$('#result').text(fromUrl.replace(urlRE, newNum));
}else{
$('#result').text('Invalid URL');
}
});
DEMO
There are not extravagant check-sums, error-checking, etc. Fromt here, use window.location or a string containing the URL if necessary.
Broken out in to a function (demo):
// Call this to replace the last digits with a new number within a url.
function replaceNumber(url, newNumber){
// regex to find (and replace) the numbers at the end.
var urlRE = /\?\d+$/;
// make sure the url end in a question mark (?) and
// any number of digits
if (urlRE.test(url)){
// replace the ?<number> with ?<newNumber>
return url.replace(urlRE, '?'+newNumber);
}
// invalid URL (per regex) just return same result
return url;
}
alert(replaceNumber('http://website.com/avatars/avatar.png?56', 57));
You could do this without regex.
var newNum = "57";
var url = "http://website.com/avatars/avatar.png?56";
var sUrl = url.split('?');
var rUrl = sUrl[0] + "?" + newNum;
alert(rUrl);
Split the URL at the ?
This returns an array.
Add the first item in the array and the ? and the new number back together.
http://jsfiddle.net/jasongennaro/7dMur/

Categories

Resources