Javascript replace one or another - javascript

I'm trying to make the replace function work when having one match or another. It's very simple as a logic so I'd like to have a very simple implementation.
I have tried:
var my_url = document.URL;
var tmpl = "?tmpl=component" || "&tmpl=component"; //This is the tricky part
location.href = my_url.replace(tmpl,"");
...but it doesn't seem to work. Any ideas please?

This is not how JavaScript works, logical OR is useless here. One possible way is using regex:
location.href = my_url.replace(/[?&]tmpl=component/, "");
Here the replace method will replace any match of tmpl=component starting with either ? or &.

You're setting tmpl to be the value of the expression "?tmpl=component" || "&tmpl=component";, which will always evaluate to "?tmpl=component", since it is the first truthy value in your or statement.
You can do this with regex in a number of ways:
my_url.replace(/?tmpl=component|&tmpl=component/, "");
my_url.replace(/[?&]tmpl=component/, "");

You could do two replacements:
location.href = my_url.replace("?tmpl=component", "").replace("&tmpl=component", "");
or you could use a regular expression: (recommended)
location.href = my_url.replace(/[?&]tmpl=component/, "");
[?&] will match either a '?' or '&' character.

Best one is:
var tmpl = (my_url.indexOf("?tmpl=component") > -1)? "?tmpl=component" : "&tmpl=component";

Related

Remove characters from url hash

Wanting to remove characters from a hash in a url
side bar create url with anchor
e.g
html/g_later_life_lett.html#3.-what-is-important?everything!
var test = window.location.hash;
$(test).replace('?', '')
so when page loads it looks af any ? and ! in hash and removes them.
thanks for help
Updated: thanks add this works fine now
var currentHash = window.location.hash;
var cleanHash = currentHash.replace(/[?!]/g, "");
window.location.hash = cleanHash;
You don't need to use jQuery. you can do this with JavaScript string replace method.
var test = "html/g_later_life_lett.html#3.-what-is-important**?-everything!**";
test = test.replace(/[?!]/g, "")
console.log(test);
The regular expression /[?!]/g selects all ? and ! from the input string.
g: stands for global. And then I am replacing all occurrences with empty string.
this will remove all the ? and ! in a string:
let str = "html/g_later_life_lett.html#3.-what-is-important?everything!"
console.log(str.replace(/[?!]/g,''));
I think you might be looking for this:
var test = window.location.hash;
var newTest = $(test).replace(/(\?|!)/gm, '');
Put the two / marks in to use a regular expression instead of simply a simple string search.
You can also test your regex here: https://regex101.com/.

Remove name from url query using regular expression

How can I remove the "/page/2/" from the url using a regular expression in javascript. Where the 2 can be any number ie. /page/5/. but "page" and the slashes will be consistently there.
mydomain.com/posts/page/2/
Use this pattern : (.*)[^\/]*\/[^\/]*\/[^\/]*\/$
Full code :
var string = 'mydomain.com/posts/page/2/';
var result = /(.*)[^\/]*\/[^\/]*\/[^\/]*\/$/.exec(string);
var wantedPath = result[1];
Testable here : http://jsfiddle.net/3h7dX/
note : page can be other thing as your number value.
Please, valid the answer to close your question if it is correct.
string = string.replace(/\/page\/\d+\//, "");
This should solve your problem. Example is under http://jsfiddle.net/AfR4D/

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>");

Simple Regex question

I want to remove this from a url string
http://.....?page=1
I know this doesn't work, but I was wondering how you would do this properly.
document.URL.replace("?page=[0-9]", "")
Thanks
It seems like you want to get rid of the protocol and the querystring. So how about just concatenating the remaining parts?
var loc = window.location;
var str = loc.host + loc.pathname + loc.hash;
http://jsfiddle.net/9Ng3Z/
I'm not entirely certain what the requirements are, but this fairly simple regex works.
loc.replace(/https?\:\/\/([^?]+)(\?|$)/,'$1');
It may be a naive implementation, but give it a try and see if it fits your need.
http://jsfiddle.net/9Ng3Z/1/
? is a regex special character. You need to escape it for a literal ?. Also use regular expression literals.
document.URL.replace(/\?page=[0-9]/, "")
The answer from #patrick dw is most practical but if you're really curious about a regular expression solution then here is what I would do:
var trimUrl = function(s) {
var r=/^http:\/\/(.*?)\?page=\d+.*$/, m=(""+s).match(r);
return (m) ? m[1] : s;
}
trimUrl('http://foo.com/?page=123'); // => "foo.com/"
trimUrl('http://foo.com:8080/bar/?page=123'); // => "foo.com:8080/bar/"
trimUrl('foobar'); // => "foobar"
You're super close. To grab the URL use location.href and make sure to escape the question mark.
var URL = location.href.replace("\?page=[0-9]", "");
location.href = URL; // and redirect if that's what you intend to do
You can also strip all query string parameters:
var URL = location.href.replace("\?.*", "");

How to replace multiple strings with replace() in Javascript

I'm guessing this is a simple problem, but I'm just learning...
I have this:
var location = (jQuery.url.attr("host"))+(jQuery.url.attr("path"));
locationClean = location.replace('/',' ');
locationArray = locationClean.split(" ");
console.log(location);
console.log(locationClean);
console.log(locationArray);
And here is what I am getting in Firebug:
stormink.net/discussed/the-ideas-behind-my-redesign
stormink.net discussed/the-ideas-behind-my-redesign
["stormink.net", "discussed/the-ideas-behind-my-redesign"]
So for some reason, the replace is only happening once? Do I need to use Regex instead with "/g" to make it repeat? And if so, how would I specifiy a '/' in Regex? (I understand very little of how to use Regex).
Thanks all.
Use a pattern instead of a string, which you can use with the "global" modifier
locationClean = location.replace(/\//g,' ');
The replace method only replaces the first occurance when you use a string as the first parameter. You have to use a regular expression to replace all occurances:
locationClean = location.replace(/\//g,' ');
(As the slash characters are used to delimit the regular expression literal, you need to escape the slash inside the excpression with a backslash.)
Still, why are you not just splitting on the '/' character instead?
You could directly split using the / character as the separator:
var loc = location.host + location.pathname, // loc variable used for tesing
locationArray = loc.split("/");
This can be fixed from your javascript.
SYNTAX
stringObject.replace(findstring,newstring)
findstring: Required. Specifies a string value to find. To perform a global search add a 'g' flag to this parameter and to perform a case-insensitive search add an 'i' flag.
newstring: Required. Specifies the string to replace the found value from findstring
Here's what ur code shud look like:
locationClean = location.replace(new RegExp('/','g'),' ');
locationArray = locationClean.split(" ");
njoi'

Categories

Resources