I know just enough JS to get in trouble so please bear with me :)
I am using the WP-Properties WordPress plugin. When searching for properties it gives all results in a common search results page. I need to theme the search results page based on part of the search string so I need a body id.
Example of a search result url:
http://website.com/property/?wpp_search[pagination]=off&wpp_search[property_type]=oasis_park&wpp_search[lot_location]=Oceano+Lot&wpp_search[availability]=-1&wpp_search[phase]=-1&wpp_search[price][min]=-1
The part I want is what comes after: "wpp_search[property_type]"
In the above case it would be "oasis_park"
And this would then create a body tag of: <body id="oasis_park">
I tried to tweak the following code to get the specific part then have it write to the body tag but I can't get it to work in my situation: remove a part of a URL argument string in php
This will only work for this specific url, as you have not provided a general pattern for each url from which you will need to extract a substring:
var myString = "http://website.com/property/?wpp_search[pagination]=off&wpp_search[property_type]=oasis_park&wpp_search[lot_location]=Oceano+Lot&wpp_search[availability]=-1&wpp_search[phase]=-1&wpp_search[price][min]=-1";
var myVar = myString.slice(myString.indexOf("&") + 27, myString.indexOf("k"));
After you have identified a general pattern in every url you wish to check, you will then have to use a combination of substr(), slice() and indexOf() to get the substring you want.
Then, try
document.body.id = myVar;
or assign an id to body (e.g. "myID") then try this:
document.getElementById('myID').id = myVar;
Related
I am wondering if how am i able to change the element data by .replace() if i use handlebar js to generate html elements.
For instance i have this role of p tag which display a row of data by handlebar js:
<p id="pre-region">{{region}}</p>
and the result of it is
1,44
and i 'd like to change it to
1+44
If you haven't had any experience of handlebar js then consider the tag be
<p id="pre-region">1,44</p>
how should i change from 1,44 to 1 +44?
UPDATE 1
Here should be an extersion for my question. I am passing the HTML element inside pre-region into an href in order to update my website by Ajax.
After i have converted all the comma in to "+" the API retrieve special character "&B2" which equal to the symbol "+" and the API goes error.
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all®ion=1%2B4
This is how may API looks like at the moment
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all®ion=1+4
should be the solution
I haven't had any experience of handlebars.js but from my point of view, you can just put the code just before the </body>:
<script>
var node = document.getElementById('pre-region');
node.innerHTML = node.innerHTML.replace(',', '+');
</script>
I'll check out the handlebars js in case it does not work.
Update:
As you mentioned in the comment, if you need to use it in the HTTP request/URL, you may handle the string using decodeURIComponent(yourstring):
decodeURIComponent('1%2B44'); // you get '1+44'
Read more about decodeURIComponent() method from this. In URL, it should be encoded as region=1%2B44 in your case; while it should be decoded if you want to use it in your JavaScript code or display in the web page.
Update 1
You should encode your string when it's used as a part of parameter of HTTP request. Therefore, it looks good if the URL is:
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all®ion=1%2B4
What you need to do is decode the string on your server side. I assume that you are in control of the server side. If you are using Node.js, you can just use decodeURIComponent() method to decode the parameter. If you're using Python or PHP as your server language, it should be something like decodeURIComponent() in that language.
Update 2
The solution above only replace the first occasion of comma to +. To solve that, simply use:
<script>
var node = document.getElementById('pre-region');
node.innerHTML = node.innerHTML.replace(/,/g, '+');
// Regular Expression is used here, 'g' for global search.
</script>
PHP has a replaceAll() method, so we can add that method to String.prototype like below if you want:
<script>
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.split(search).join(replacement);
}
// Another method to replace all occasions using `split` and `join`.
</script>
Alright, so this is my first answer ever on stack overflow so I'm alien to this whole thing but here we go:
You could try this code in another js file that runs after handlebars:
var pre = $('#pre-region'); // defines a variabe for the element (same as
// document.getElementById('pre-region'))
var retrievedRegion = pre.innerHTML;
var splitten = retrievedRegion.split(',');
var concatenated = parseInt(split[0]) + parseInt(split[1])
retrievedRegion.innerHTML = "'" + concatenated) + "'";
or using replace():
retrievedRegion.replace(',','+')
I've been going through and trying to find an answer to this question that fits my need but either I'm too noob to make other use cases work, or their not specific enough for my case.
Basically I want to use javascript/jQuery to replace any and all ampersands (&) on a web page that may occur in a links href with just the word "and". I've tried a couple different versions of this with no luck
var link = $("a").attr('href');
link.replace(/&/g, "and");
Thank you
Your current code replaces the text of the element within the jQuery object, but does not update the element(s) in the DOM.
You can instead achieve what you need by providing a function to attr() which will be executed against all elements in the matched set. Try this:
$("a").attr('href', function(i, value) {
return value.replace(/&/g, "and");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
link
link
Sometimes when replacing &, I've found that even though I replaced &, I still have amp;. There is a fix to this:
var newUrl = "#Model.UrlToRedirect".replace(/&/gi, '%').replace(/%amp;/gi, '&');
With this solution you replace & twice and it will work. In my particular problem in an MVC app, window.location.href = #Model.UrlToRedirect, the url was already partially encoded and had a query string. I tried encoding/decoding, using Uri as the C# class, escape(), everything before coming up with this solution. The problem with using my above logic is other things could blow up the query string later. One solution is to put a hidden field or input on the form like this:
<input type="hidden" value="#Model.UrlToRedirect" id="url-redirect" />
then in your javascript:
window.location.href = document.getElementById("url-redirect").value;
in this way, javascript won't take the c# string and change it.
I'm hoping to call a line of text by using a simple URL parameter. Say I had an ordered list in javascript and on load of url example.com/?i=14 would get the 14th line in my list and place it where desired.
How can I achieve this?
I'm not sure what you mean by "call a line of text," but maybe you could do this:
var url = window.location.href;
var queryPos = url.indexOf('i=');
var param = url.substr(queryPos + 'i='.length);
Now param will contain the value of the parameter and you could use it to fetch whatever.
But since you're trying to access a value from a URL with JavaScript, it might be better to make use of # as explained here: How do I get the value after hash (#) from a URL using jquery (there are non-jquery answers as well)
Hopefully this is what you need.
To place an array element where you need it on document load
<div id="placeHere"></div>
In JS
document.body.onload = function(){
document.getElementById('placeHere').innerHTML = array[14];
}
jQuery
$(document).ready(function(){
$('#placeHere').html(array[14]);
})
Let's say I have the following url string:
www.mysite.com?this&that&theOtherThing
I know how to add query strings to any link, but am unaware of how to remove one.
For instance, I know I can add a query string by doing the following:
//just add within the href
submit
or
//set the href within jquery
$('button').attr('href', currentUrl + '&that');
How would I remove that same query on click?
I tried the following, but got an NaN error:
$('button').attr('href', currentUrl - '&that');
Does anyone have advice on how to remove a query?
First, you want to replace "?that", not "&that". Second, you have an a tag that doesn't have an id, but you're setting the 'href' attribute of an element with the id of 'button', which doesn't appear in your code snippet.
You got a NaN error because you're trying to subtract "?that" from a string. Instead, use string.replace("?that", "") - which will remove the "%that", but not anything after it (if there is something). If there is something after "&that" in your string, get the indexOf("?that") and then set the string to a substring of itself like so:
html:
Click me
Javascript:
var urlString = $("#linktoModify").prop("href");
urlString = urlString.toString().substring(0, urlString.indexOf("?"));
$("#linkToModify").prop("href", urlString);
Also, keep in mind that your question is a bit misleading. You're trying to edit a string with javascript, not remove a query string. Query strings are readonly and cannot be removed, but you can easily modify a string, which appears to be what you're trying to do.
function remove_args(a, url, arg){
a.attr('href', url.replace(arg,''));
}
html
URL
try something like this. just a small scenario
Can anyone help me. I don't use Client-side Javascript often with HTML.
I would like to grab the current url (but only a specific directory) and place the results between a link.
So if the url is /fare/pass/index.html
I want the HTML to be pass
This is a quick and dirty way to do that:
//splits the document.location.href property into an array
var loc_array=document.location.href.split('/');
//have firebug? try a console.log(loc_array);
//this selects the next-to-last member of the array.
var directory=loc[loc.length-2]
url = window.location.href // Not particularly necessary, but may help your readability
url.match('/fare/(.*)/index.html')[1] // would return "pass"
There may be an easier answer, but the simplest thing I can think of is just to get the current URL with window.location and use some type of parsing to get which directory you are looking for.
Then, you can dynamically append the HTML to your page.
This may get you started:
var linkElement = document.getElementById("whatever");
linkElement.innerHTML = document.URL.replace(/^(?:https?:\/\/.*?)?\/.*?\/(.*?)\/.*?$/i,"$1");