Removing a query string using regex in java script - javascript

I have a requirement of removing a query parameter coming with a REST API call. Below are the sample URLs which need to be considered. In each of this URL, we need to remove 'key' parameter and its value.
/test/v1?key=keyval&param1=value1&param2=value2
/test/v1?key=keyval
/test/v1?param1=value1&key=keyval
/test/v1?param1=value1&key=keyval&param2=value2
After removing the key parameter, the final URLs should be as follows.
/test/v1?param1=value1&param2=value2
/test/v1?
/test/v1?param1=value1
/test/v1?param1=value1=&param2=value2
We used below regex expression to match and replace this query string in php. (https://regex101.com/r/pK0dX3/1)
(?<=[?&;])key=.*?($|[&;])
We couldn't use the same regex in java script. Once we use it in java script it gives some syntax errors. Can you please help us to figure out the issue with the same regex ? How can we change this regex to match and remove query parameter as mentioned above?

Obviously lookbehind isn't supported in Javascript hence your regex won't work.
In Javascript you can use this:
repl = input.replace(/(\?)key=[^&]*(?:&|$)|&key=[^&]*/gmi, '$1');
RegEx Demo
Regex is working on 2 paths using regex alternation:
If this query parameter is right after ? then we grab till & after parameter and place ? back in replacement.
If this query parameter is after & then &key=value is replaced by an empty string.

The regex works in PHP but not in Javascript because Javascript does not support lookbehind.
The easiest fix here would be to replace the lookbehind (?<=[?&;]) with the equivalent characters in a capturing group ([?&;]) and use a backreference ($1) to insert this bit back into the replacement string.
For example:
var path = '/test/v1?key=keyval&param1=value1&param2=value2';
var regex = /([?&;])key=.*?($|[&;])/;
console.log(path.replace(regex, '$1'); // outputs '/test/v1?param1=value1&param2=value2'
Not convinced regex would be the most reliable way of removing a query parameter, but that's a different story :-)

Just in case you want to do it without a regex, here is a function that will do the trick:
var removeQueryString = function (str) {
var qm = str.lastIndexOf('?');
var path = str.substr(0, qm + 1);
var querystr = str.substr(qm + 1);
var params = querystr.split('&');
var keyIndex = -1;
for (var i = 0; i < params.length; i++) {
if (params[i].indexOf("key=") === 0) {
keyIndex = i;
break;
}
}
if (keyIndex != -1) {
params.splice(keyIndex, 1);
}
var result = path + params.join('&');
return result;
};

The lookbehind feature isn't available in javascript, so to test the character before the key/value, you must match it. To make the pattern works whatever the position in the query part of the url, you can use an alternation in a non-capturing group, and you capture the question mark:
url = url.replace(/(?:&|(\?))key=[^&#]*(?:(?!\1).)?/, '$1');
Note: the # is excluded from the character class to prevent the fragment part (if any) of the url to be matched with key value.

Related

regex get part of the link

https://www.example.com/uk/This-Part-I-Need-To-Get/F1ST2/sometext/
need to get "This-Part-I-Need-To-Get", with "-" symbols and capital letters at the wordstart.
All I managed to do is "/([A-Z-])\w+/g", that returns
"This" "-Part" "-I" "-Need" "-To" "-Get" "F1ST2", but I don`t need "F1ST2".
How should I do it?
It might depend on URL format, but at this point:
var url = 'https://www.example.com/uk/This-Part-I-Need-To-Get/F1ST2/sometext/';
console.log(url.split('/')[4])
Try this regex
/([A-Z][a-z]|-[A-Z]|-[A-Z][a-z]-|-[A-Z]-)\w+/g
Here is a SNIPPET
var url = 'https://www.example.com/uk/This-Part-I-Need-To-Get/F1ST2/sometext/';
console.log(url.match(/([A-Z][a-z]|-[A-Z]|-[A-Z][a-z]-|-[A-Z]-)\w+/g).join(''))
As #MichałSałaciński said, you should consider using split function.
BTW, if you wan't to use regular expressions, then this one will work if url format does not change : [^\/]+(?=(?:\/\w+){2}\/)
Demo
var re = /[^\/]+(?=(?:\/\w+){2}\/)/
var url = "https://www.example.com/uk/This-Part-I-Need-To-Get/F1ST2/sometext/"
if(re.test(url)) {
// URL match regex pattern, we can safely get full match
var value = re.exec(url)[0];
console.log(value);
}
Explanation
[^\/]+ Any character but a slash n times
(?=...) Followed by
(?:\/\w+){2}\/ a slash and any word character (2 times) then a slash
Solution 2
This one also works using captured group 1: :\/\/[^\/]+\/[^\/]+\/([^\/]+)
Demo
var re = /:\/\/[^\/]+\/[^\/]+\/([^\/]+)/;
var url = "https://www.example.com/uk/This-Part-I-Need-To-Get/F1ST2/sometext/";
if(re.test(url)) {
// URL match regex pattern, we can safely get group 1 value
var value = re.exec(url)[1];
console.log(value );
}

RegExp to filter characters after the last dot

For example, I have a string "esolri.gbn43sh.earbnf", and I want to remove every character after the last dot(i.e. "esolri.gbn43sh"). How can I do so with regular expression?
I could of course use non-RegExp way to do it, for example:
"esolri.gbn43sh.earbnf".slice("esolri.gbn43sh.earbnf".lastIndexOf(".")+1);
But I want a regular expression.
I tried /\..*?/, but that remove the first dot instead.
I am using Javascript. Any help is much appreciated.
I would use standard js rather than regex for this one, as it will be easier for others to understand your code
var str = 'esolri.gbn43sh.earbnf'
console.log(
str.slice(str.lastIndexOf('.') + 1)
)
Pattern Matching
Match a dot followed by non-dots until the end of string
let re = /\.[^.]*$/;
Use this with String.prototype.replace to achieve the desired output
'foo.bar.baz'.replace(re, ''); // 'foo.bar'
Other choices
You may find it is more efficient to do a simple substring search for the last . and then use a string slicing method on this index.
let str = 'foo.bar.baz',
i = str.lastIndexOf('.');
if (i !== -1) // i = -1 means no match
str = str.slice(0, i); // "foo.bar"

How to find in javascript with regular expression string from url?

Good evening, How can I find in javascript with regular expression string from url address for example i have url: http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/ and I need only string between last slashes (/ /) http://something.cz/something/string/ in this example word that i need is mikronebulizer. Thank you very much for you help.
You could use a regex match with a group.
Use this:
/([\w\-]+)\/$/.exec("http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/")[1];
Here's a jsfiddle showing it in action
This part: ([\w\-]+)
Means at least 1 or more of the set of alphanumeric, underscore and hyphen and use it as the first match group.
Followed by a /
And then finally the: $
Which means the line should end with this
The .exec() returns an array where the first value is the full match (IE: "mikronebulizer/") and then each match group after that.
So .exec()[1] returns your value: mikronebulizer
Simply:
url.match(/([^\/]*)\/$/);
Should do it.
If you want to match (optionally) without a trailing slash, use:
url.match(/([^\/]*)\/?$/);
See it in action here: http://regex101.com/r/cL3qG3
If you have the url provided, then you can do it this way:
var url = 'http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/';
var urlsplit = url.split('/');
var urlEnd = urlsplit[urlsplit.length- (urlsplit[urlsplit.length-1] == '' ? 2 : 1)];
This will match either everything after the last slash, if there's any content there, and otherwise, it will match the part between the second-last and the last slash.
Something else to consider - yes a pure RegEx approach might be easier (heck, and faster), but I wanted to include this simply to point out window.location.pathName.
function getLast(){
// Strip trailing slash if present
var path = window.location.pathname.replace(/\/$?/, '');
return path.split('/').pop();
}
Alternatively you could get using split:
var pieces = "http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/".split("/");
var lastSegment = pieces[pieces.length - 2];
// lastSegment == mikronebulizer
var url = 'http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/';
if (url.slice(-1)=="/") {
url = url.substr(0,url.length-1);
}
var lastSegment = url.split('/').pop();
document.write(lastSegment+"<br>");

Matching hashes using regex, but not when they are part of an url

I am struggling with a regex in javascript that needs the text after # to the first word boundary, but not match it if it is part of an url. So
#test - should match test
sometext#test2 - should match test2
xx moretext#test3 - should match test3
http://test.com#tab1 - should not match tab1
I am replacing the text after the hash with a link (but not the hash character itself). There can be more than one hash in the text, and it should match them all (I guess I should use /g for that).
Matching the part after the hash is quite easy: /#\b(.+?)\b/g, but not matching it if the string itself starts with "http" is something I cannot solve. I should probably use a negative look-around, but I am having problems getting my head around that.
Any help is greatly appreciated!
Try this regex using a negative lookahead instead since JS doesn't support lookbehinds:
/^(?!http:\/\/).*#\b(.+?)\b/
You may want to check for www too, depending on your conditions.
Edit: Then you can do this:
str = str.replace(re.exec(str)[1], 'replaced!');
http://jsfiddle.net/j7c79/2/
Edit 2: Sometimes a regex alone is not the way to go if it gets too complicated. Try a different approach:
var txt = "asdfgh http://asdf#test1 #test2 woot#test3";
function replaceHashWords(str, rep) {
var isUrl = /^http/.test(str), result = [];
!isUrl && str.replace(/#\b(.+?)\b/g, function(a,b){ result.push(b); });
return str.replace((new RegExp('('+ result.join('|') +')','g')), rep);
}
alert(replaceHashWords(txt, 'replaced!'));
// asdfgh http://asdf#replaced! #replaced! woot#replaced!
As regex is, often (if not always), quite expensive to use, I'd suggest using basic string, and array, methods to determine whether a given set of characters represents an URL (though I'm assuming that all URLS will start with the http string):
$('ul li').each(
function() {
var t = $(this).text(),
words = t.split(/\s+/),
foundHashes = [],
word = '';
for (var i = 0, len = words.length; i < len; i++) {
word = words[i];
if (word.indexOf('http') == -1 && word.indexOf('#') !== -1) {
var match = word.substring(word.indexOf('#') + 1);
foundHashes.push(match);
}
}
// the following just shows what, if anything, was found
// and can definitely be safely omitted
if (foundHashes.length) {
var newSpan = $('<span />', {
'class': 'matchedWords'
}).text(foundHashes.join(', ')).appendTo($(this));
}
});
JS Fiddle demo (with some timing information printed to the console).
References:
jQuery:
appendTo().
each().
text().
'Vanilla' JavaScript
Array.join().
String.indexOf().
String.split().
String.substring().
This would require a lookbehind, something sadly lacking from JavaScript's capabilities.
However, if your subject string is some HTML and those URLs are in href attributes, you can create a document out of it and search for text nodes, only replacing their nodeValues instead of the whole HTML string.

Javascript Regex with Match

I am trying to extract a number from a string with regular expression as I am told this would be the best approach for what I am wanting to do.
Here is the string:
http://domain.com/uploads/2011/09/1142_GF-757-S-white.jpg&h=208&w=347&zc=1&q=90&a=c&s=&f=&cc=&ct=
and I am trying to extract 208 from (height) from the string. so I know I have to look for "&h=" in the expression but I don't know what to do after that. How can I match between that and the next "&" but not include them as well...
Thanks..
Regular expression to match an h url parameter containing an integer value.
[&?]h=(\d+)
The Javascript:
var match = /[&?]h=(\d+)/.exec(url_string);
alert(match[1]);
Learn more about Regular Expressions.
To get the entire h=xxxx parameter, you can use this generic function (which you can reuse elsewhere for other purposes) and pass it the desired key:
function getParameterFromURL(url, key) {
var re = new RegExp("[&?]" + key + "=([^&]*)");
var matches = url.match(re);
if (matches) {
return(matches[1]);
}
return(null);
}
var url = "http://domain.com/uploads/2011/09/1142_GF-757-S-white.jpg&h=208&w=347&zc=1&q=90&a=c&s=&f=&cc=&ct=";
var parm = getParameterFromURL(url, "h");
See http://jsfiddle.net/jfriend00/86MEy/ for a working demo.

Categories

Resources