So I have a URL which is mentioned in the following example; I want to change the value of pageToken to "baz"; but my following attempt is replacing pageToken as well; what is the right way to just change the value of pageToken?
var url = "https://www.googleapis.com/youtube/v3/search?&pageToken=CDIQAQ&foo=bar"
var res = url.replace(/pageToken=\w*/g, "baz");
console.log(res);
//res is now: https://www.googleapis.com/youtube/v3/search?&baz&foo=bar, but my desired output is https://www.googleapis.com/youtube/v3/search?&pageToken=baz&foo=bar
Thanks
The easy way is to include "pageToken=" in the new text:
var res = url.replace(/pageToken=\w*/g, "pageToken=baz");
This will work also:
var res = url.replace(/(pageToken=)\w*/g, "$1baz");
Related
I'm building a dictionary word definition search engine which has a #submit button and #word input. I also have a JSON dictionary(Github link). I don't know how to select what word definition to use depending on what the user types.
I have already tried putting the input.value() as a var to the json object query:
var uInVal = input.value();
document.getElementById("p1").innerHTML = words.uInVal)
Can someone help me?
My Code:
var words;
var input;
function setup() {
loadJSON("dictionary.json", gotData);
var button = select('#submit');
button.mousePressed(keyDraw);
input = select('#word');
}
function gotData(data){
words = data;
}
function keyDraw(){
document.getElementById("p1").innerHTML; //This is where the word definition should get printed
}
In the future, please try to work with a simpler example. Something like this would show your problem in a runnable example:
var jsonString = '{"x": 42, "y":100}';
var jsonObject = JSON.parse(jsonString);
This is also easier for you to work with. Now that you have this, I'd google something like "javascript get value from property name" for a ton of results.
But basically, there are two ways to get the value of a property:
var xOne = jsonObject.x;
var xTwo = jsonObject['x'];
console.log(xOne);
console.log(xTwo);
This is what you're trying to do:
var varName = 'x';
var myX = jsonObject.varName;
This won't work, because jsonObject doesn't have any field named varName. Instead, you want to access the x field. To do that, you can use bracket [] notation:
var myX = jsonObject['x'];
Thats my code:
const searchTerm = `?term=${this.term}`;
const routeWithoutTerm = this.$route.fullPath.replace(searchTerm , '');
I want to remove searchTerm from this.$route.fullPath and save it in routeWithoutTerm, but this is obviously the wrong way. It just replaces nothing. How can I achieve this?
EDIT: Lets just say that at execution this.term = 'help' and this.$route.fullPath = 'search/help?term=help' and I want to remove ?term=help
I finally found my problem.
I was having umlauts(ö, ä, ü) in my searchTerm so I had to use encodeURI() on my searchTerm first.
try this to remove search param:
const url = 'https://example.com/posts?page=5&sort=desc';
const urlObj = new URL(url);
urlObj.search = '';
const result = urlObj.toString();
console.log(result); // https://example.com/posts
source
Use substring() function to get the part you want and use replace() to replace it with whatever you want
const const1 = "adios";
const const2 = "muchasgracias";
var result = const2.replace(const2.substring(0,5), const1);
console.log(result);
I want to filter out a specific parameter out of the URL. I have the following situation:
The page got loaded (for example: http://test.com/default.aspx?folder=app&test=true)
When the page is loaded a function is called to push a entry to the history (pushState): ( for example: http://test.com/default.aspx?folder=app&test=true&state=1)
Now I want to call a function that reads all the parameters and output all these parameters expect for the state. So that I end up with: "?folder=app&test=true" (just a string value, no array or object). Please keep in mind that I do not know what all the names of the parameters are execpt for the state parameter
What I have tried
I know I can get all the parameters by using the following code:
window.location.search
But it will result in:
?folder=app&test=true&state=1
I try to split the url, for example:
var url = '?folder=app&test=true&state=1';
url = url.split('&state=');
console.log(url);
But that does not work. Also because the state number is dynamic in each request. A solution might be remove the last parameter out of the url but I also do not know if that ever will be the case therefore I need some filtering mechanisme that will only filter out the
state=/*regex for a number*/
To achieve this you can convert the querystring provided to the page to an object, remove the state property of the result - assuming it exists - then you can convert the object back to a querystring ready to use in pushState(). Something like this:
var qsToObj = function(qs) {
qs = qs.substring(1);
if (!qs) return {};
return qs.split("&").reduce(function(prev, curr, i, arr) {
var p = curr.split("=");
prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
return prev;
}, {});
}
var qs = '?'; // window.location.search;
var obj = qsToObj(qs);
delete obj.state;
console.log(obj);
var newQs = $.param(obj);
console.log(newQs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Credit to this answer for the querystring to object logic.
I would agree with Rory's answer, you should have an object to safely manipulate params. This is the function that I use.
function urlParamsObj(source) {
/* function returns an object with url parameters
URL sample: www.test.com?var1=value1&var2=value2
USE: var params = URLparamsObj();
alert(params.var2) --> output: value2
You can use it for a url-like string also: urlParamsObj("www.ok.uk?a=2&b=3")*/
var urlStr = source ? source : window.location.search ? window.location.search : ""
if (urlStr.indexOf("?") > -1) { // if there are params in URL
var param_array = urlStr.substring(urlStr.indexOf("?") + 1).split('&'),
theLength = param_array.length,
params = {},
i = 0,
x;
for (; i < theLength; i++) {
x = param_array[i].toString().split('=');
params[x[0]] = x[1];
}
return params;
}
return {};
}
A much simpler way to do this would be:
let url = new URL(window.location.href)
url.searchParams.delete('state');
window.location.search = url.search;
You can read about URLSearchParams.delete() in the MDN Web Docs.
Sorry if this is wrong just as i think &state=1,2,3,4,5,6 is absolute its just depends on number to pick states just like my web
var url = '?folder=app&test=true&state=1';
url = url.substring(0, url.indexOf('&s'));
$('#demo').text(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='demo'></span>
var url = '?folder=app&test=true&state=1';
url = url.split('&folder=');
console.log(url);
When i try to get the type of an element using the below code it works.
var bodyContent = JSON.parse(response.content);
response.content = typeof bodyContent.CompanyList.Company.Name;
Output response for above was String
Whereas if i try it in the below approach this does not work for the same JSON message. Please help
var bodyContent = JSON.parse(response.content);
var nameHolder = "CompanyList.Company.Name";
response.content = typeof bodyContent[nameHolder];
Output was undefined
That's because it's a nested object, you can't just pass a period delimited name and have it recursively drill down the tree (you'll have to implement that yourself).
It's the difference between
bodyContent["CompanyList"]["Company"]["Name"]; // former
and
bodyContent["CompanyList.Company.Name"]; // latter
There are 2 solutions for this issue.
You have to parse the nameHolder path. Reference: Accessing nested JavaScript objects with string key
or use eval but I'll not write about this since it's not a good practise.
It looks for a property called "CompanyList.Company.Name".
This works:
var bodyContent = JSON.parse(response.content);
var list = "CompanyList";
var company = "Company";
var name = "Name";
response.content = typeof bodyContent[list][company][name];
Just wondering if anyone knows why I can't get both key/values within a 'where' to be dynamic? I can do the value through a variable, that works perfectly, but I can't seem to get the key to run off a variable at all.
My fiddle is here: http://jsfiddle.net/leapin_leprechaun/eyw6295q/ the code I'm trying to get working is below.
I'm new to backbone so there's a chance this is something you can't do and I just don't know about it yet!
var newCollection = function(myCollection,prop,val){
alert('myprop: ' + prop);
alert('val: ' + val);
var results = myCollection.where({
//prop: val this doesn't work even if I put a string above it to make sure the value coming through is fine
//prop: "Glasnevin" //this doesn't work
"location" : val //this works
});
var filteredCollection = new Backbone.Collection(results);
var newMatchesModelView = new MatchesModelView({collection: filteredCollection });
$("#allMatches").html(newMatchesModelView.render().el);
}
Thanks for your time
Your code does not work because the key "prop" is always interpreted literally, as a string. So, you search by {"prop": val} not by {"location": val}. There are couple ways how to solve this problem
1
var where = {};
where[prop] = val;
var results = myCollection.where(where);
2
var results = myCollection.where(_.object([prop], [val]));
There are a few ways to do this, the simplest would be to just create a placeholder object, and assign the key and value:
var query = {};
query[prop] = val;
var results = myCollection.where(query);
Or, if that's too verbose and you are alright with a very small amount of overhead, you could use _.object
var results = myCollection.where(_.object([prop], [val]);