apple .replace() Html element generate by handlebar js - javascript
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(',','+')
Related
Get a text from Html string using JavaScript
Need to extract one key from a string containing HTML doc using JavaScript /NodeJs. I am getting a HTML Page as response of one service which includes a key, which need to be extracted, the key is inside a tag and the page is heavily nested , even after converting to JSON also didn't help. Tried with regular expression that also not fetching all results (since there are many matches with tag). The key in tag is like the following: <script> $function(){ //some codes app.init({ //some code access : {"AccessKey": "dwdfsfcnoidxjbvukv"} }); //some code </script>
Use this regex /\{"AccessKey":(.*)\}/ which I think suitable for this problem. var data = `<script> $function(){ app.init({ access : {"AccessKey": "dwdfsfcnoidxjbvukv"} }); </script>`; var result = data.match(/\{"AccessKey":(.*)\}/); console.log(result[1]);
Javascript: add body ID based on part of search results url
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;
JSON from Newtonsoft to JavaScript
So, I have a some json data which I create in my controller like so: Notes = JsonConvert.SerializeObject(contact.Notes.OrderBy(x => x.DateLogged).Select(x => new { id = x.Id, date = x.DateLogged, content = x.Content, logged = x.Username })) This then gets passed to the view, now which statment can I do to achieve the results of having a variable contain that json data: var data = '#Html.Raw(Model.Notes)' or var data = JSON.parse('#Html.Raw(Model.Notes)'); EDIT the content variable holds some "\n" which when passed to the view using the first choice from above generates an error, saying Unexpected Token it only does it with \n so what is going wrong here? the bottom method doesn't quite work.
var data = JSON.parse('#Html.Raw(Model.Notes)'); This doesn't work - you can't put a JSON literal inside a JavaScript string. Any backslash in it will be an escape character to the JavaScript parser, not the JSON parser. A newline comes out like: var data = JSON.parse('{"content": "abc\ndef"}'); which means the string you are asking JSON to parse is: {"content": "abc def"} which is not valid as you can't have a literal newline in a JSON string. To do this with JSON.parse you would have to JS-string-literal encode the JSON output, so you would end up with "abc\\ndef". The alternative would be to include the JSON directly in the script block as var data = #Html.Raw(Model.Notes);, but there are problems with this to do with the differences between JS and JSON (primarily characters U+2028 and U+2029) and the enclosing HTML context (ie what the sequence </script does). Getting the escaping right here is harder than it looks, so you should avoid injecting anything into a <script> block. Better to put in-page JSON data in a data- attribute and read it from the DOM; this way you can use the normal HTML escaping Razor gives you by default. <div id="notes" data-notes="#Model.Notes"> ... var data = JSON.parse(document.getElementById('notes').getAttribute('data-notes'));
bobince is obviously correct in what he says, it makes so much sense, thanks for that. However, my solution was to simply do: var data = #Html.Raw(Model.Notes); Because, Newtonsoft already has converted it to a proper JSON format, so all it needs to do, is be assigned to a variable to be manipulated. I think grabbing the content from a the HTML DOM is a bit too much for this.
Pass text parameter to the url variable at .load function on jQuery
I am trying to pass a text by parameter (with whitespaces) to the load function and it seems it doesn't work. Currently i am doing this: var text ="hello world this is an example"; $("#selector").load("http://"+ document.domain + "/myfunction/"+text); Is there any way to do it? If i call the function by URL directly, not with jQuery, it works well. Thanks.
You should encode "text" with encodeURI: var text = encodeURI('hello world this is an example'); This will ensure that your whitespaces are replaced with url compatible characters, which your browser does internally when you're directly accessing the url.
Calling the function by URL directly might works well in your browser. But it is not future proof. You must encode your url with encodeURI function. After appending user given data. var text ="hello world this is an example", url = encodeURI("http://"+ document.domain + "/myfunction/"+ text); $("#selector").load(url); And on server side you can do something like this to get back user entered data. $data = urldecode($_SERVER['REQUEST_URI']); // This will return // /myfunction/hello world this is an example
Create 2d array from string
I have the following string : [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],] How can I create a 2d array of strings from it ? EDIT I've removed html tags since they're not the problem here. Also I'd like to do it without using any additional libs to keep it lightweight.
Except from the HTML tags in it, it would be valid JSON. You could remove the HTML tags and parse it using any library that handles JSON, like jQuery: var arr = $.parseJSON(theString.replace(/<br\/>/g,'')); It would also be valid Javascript code with the HTML tags removed, so if you have full control over where the string comes from so that you are certain that it can never contain any harmful code, you could use the eval function to execute the string: // Warning: 'eval' is subject to code injection vulnerabilities var arr = eval(theString.replace(/<br\/>/g,''));
You will need to remove the <br/> from the string. Then you should be able to do: var my2darray = eval(mystring);