I am learning JavaScript and I see %value% in a code but I do not know what does it mean or how to use it. Can anyone please help me explain to me. Thank you very much.
var formattedLocation = HTMLworkLocation.replace("%data%", work.jobs[job].location);
"%data%" is just a literal string. This code will take the value of HTMLWorkLocation, look for the first occurrence of %data% in it, and replace that with the value of work.jobs[job].location, and store the resulting string in formattedLocation.
var work = {
jobs: [{
location: "Home office"
}]
};
var job = 0;
var HTMLworkLocation = "John is located at %data%";
var formattedLocation = HTMLworkLocation.replace("%data%", work.jobs[job].location);
console.log(formattedLocation);
This is probably part of a template system that's used to replace placeholders like %data% with values that come from a table.
You're using string.replace which takes a string or regular expression as it's first argument. Based on the code you posted it looks like you're looking for the string "%data%" (or whatever string you're looking for) in HTMLworkLocation and replacing it with the value in work.jobs[job].location. Then it is being stored in formattedLocation.
I would put a debugger; line after that line of code so you can see what the values are in the debugger console. That might help make more sense of things.
Here is more info on the str.replace method with some examples
Related
I'm receiving a string like obj{a="foo",b="bar",c=3,d=4.0} inside a nodejs environment I'm working in and I'm trying to convert this String into a reference-able Object like this:
{
a : "foo",
b : "bar",
c : 3,
d : 4.0
}
Assigned to obj of course.
I've used a myriad of formatting tricks but whenever I call JSON.parse() I get unexpected character errors. Usually on the first alpha-character it sees.
My next step is to write several nested loops to make all of the assignments manually but I'm hoping someone can point me in the right direction on how to parse this.
EDIT: Ok there's a little more to the story and I thought I should omit it but I guess explaining everything would be helpful.
The actual data packet that I'm receiving looks like this.
ack{a="000000061",b=0,c=2.0}\rb{a=244.0,b=255,c=4.0}\rc{a=6.0,b=55,c=55}endack;
So yeah that's the actual string I'm trying to parse into three distinct accessible Objects. I know I'm having a brain fart from a long day but yeah it's giving me a run for my money right now.
First replace the "=" with ":" and remove the obj infront
str = str.replace(/=/g, ":").replace("obj{", "{")
Since it's not in correct json format (but can be read by js parser) we can't use JSON.parse but we can use eval
eval("var obj = " + str);
Obvious there are some assumptions with this technique such that = always mean colon and you won't have obj{ as text (but the latter can be fixed with a simple substring method)
Keep in mind eval is also considered evil so use at your own risk. Imagine if the user were to send bad data, they could easily get into your parser and run something malicious. But hopefully this will give you an idea or inspiration to a better solution.
You can go a step further and use
str = 'obj{a="foo",b="bar",c=3,d=4.0}'
str = str.substr(3,str.length).replace(/([{,])([\w])=/g, '$1\"$2\":');
var obj = JSON.parse(str);
I'm trying to convert a currency string to a number. I'm using a replace function with a regexp that I've used successfully in a similar context before.
The currency string is captured here, in part of an "each" loop:
var unitGridPrice = jQuery(this).find(".clsPriceGridDtlPrice").html();
The result is that unitGridPrice is a currency string, something like "$2.75". I'm trying to convert it to a number here:
var priceToConvert = unitGridPrice;
var unitGridPriceNo = Number(priceToConvert.replace(/[^0-9\.]+/g, ''));
However with that last line in place, the script will not run.
If I use the value of priceToConvert it correctly displays the currency text string, so I believe the string feeding the replace function is correct.
if I change "var priceToConvert = unitGridPrice" to "var priceToConvert = "$2.75" the script properly returns 2.75. I can copy and past the value that unitGridPrice displays into the text string I'm testing with and it works, but with the variable there the script dies.
I've tried removing the regex, changing the replace to .replace('$', '') and again the script stops with the variable in place but works if I test with a fixed string.
I'm really stumped. Help??!! Thank you!!!
i had some problem while try to get number from string also, little time ago. the problem is the regex, so i changed the regex like code below.
var id = element.name.replace ( /[^\d.]/g, '' );
element.name above is like input_21,input_22, etc. and i wanna get only the number(21,22).
hope it can help you. :)
okay I give up. Here's my code:
var re = /href="(http.*\.jpg)"/g;
var mp3s = body.match(re);
it finds pictures, but it returns href="http://www.picture.com/smthg.jpg"
instead of returning http://www.picture.com/smthg.jpg
any idea why?
The result from match() is actually an object.
I think you need to access the first element on that object.
For example:
body.match(re)[1]
This is where the actual result is kept.
Shameless self-promotion:
I've written a small guide for me, I can never remember how to use these either. It's here: http://queirozf.com/reminders/javascript-regular-expressions-usage-reminder
try
var re = /(http.*\.jpg)/g;
var mp3s = body.match(re);
since you don't need the href.
You want to match the regular expression, but then return just the portion in brackets.
To do this, call the regular expressions exec method. For example:
var body = 'stuff stuff morestuff href="http://www.picture.com/smthg.jpg" and some more stuff';
var re = /href="(http.*\.jpg)"/g;
var regexResults = re.exec(body);
var mp3s = regexResults[1];
alert(mp3s);
Having given you this answer, I must implore you to find a different way to solve this problem. You cannot parse HTML using regular expressions. No matter how sophisticated your regular expression gets, there will be a legal HTML example which will break it.
I want to find anything that comes after s= and before & or the end of the string. For example, if the string is
t=qwerty&s=hello&p=3
I want to get hello. And if the string is
t=qwerty&s=hello
I also want to get hello
Thank you!
\bs=([^&]+) and grabbing $1should be good enough, no?
edit: added word anchor! Otherwise it would also match for herpies, dongles...
Why don't you try something that was generically aimed at parsing query strings? That way, you can assume you won't run into the obvious next hurdle while reinventing the wheel.
jQuery has the query object for that (see JavaScript query string)
Or you can google a bit:
function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
looks useful; for example with
http://www.bloggingdeveloper.com?author=bloggingdeveloper
you want to get the "author" querystring's value:
var author_value = getQuerystring('author');
The simplest way to do this is with a selector s=([^&]*)&. The inside of the parentheses has [^&] to prevent it from grabbing hello&p=3 of there were another field after p.
You can also use the following expression, based on the solution provided here, which finds all characters between the two given strings:
(?<=s=)(.*)(?=&)
In your case you may need to slightly modify it to account for the "end of the string" option (there are several ways to do it, especially when you can use simple code manipulations such as manually adding a & character to the end of the string before running the regex).
I have tried Split("?") and Split('?'). Both give the same error (link.split is not a function), so i assume that there is a way to be able to split but not using this Split?
Maybe jQuery?
Edit: Got it, it should be href.split. So as jordan said, it was not a string. So i used x.href.split("?") and it worked like a charm.
Jetpack just uses JavaScript so this should work:
var str = "My.string";
str.split("."); // => [ "My", "string" ]
If it tells you "split is not a function" then it probably means your variable doesn't hold a string like you think it does.
If the object is not already a string, convert it first.
myObject.toString().split("?");