String interpolation using react - javascript

I am trying to figure out the React way of doing the following:
I have an url that I get from my server with placeholders for url parameters:
http://localhost/{someSlug}/?FirstParameter={FirstParameter}&SecondParamter={SecondParameter}
under the url I have an input field for each parameter, or slug, which should update the url using state.
I solved it quickly by using jquery and regex. I wrapped the Parameter value in a <span data="{FirstParameter}">{FirstParameter}</span>.
http://localhost/<span data="{someSlug}">{someSlug}</span>/?FirstParameter=<span data="{FirstParameter}>{FirstParameter}</span>&SecondParamte‌​r=<span data="{SecondParameter}">{SecondParameter}<span>
Which allowed me to find and replace the value when ever the input changes.
const $el = $(`span[data="{${prop}}"]`);
$el.text(e.target.value);
if ($el.text().trim() === '') {
$el.text(`{${prop}}`)
}
But I am wondering how I would solve this without jQuery.

Related

How to correctly extract part of a string js?

I have a URL and I need to isolate a certain value from it, and to be more precise, the value after numberType=.
There may or may not be an ampersand after this value. How can I implement this with a generic function?
Examples
http://localhost:8080/type/3259/?filters=901&numberType=77
http://localhost:8080/type/3259/?filters=901&numberType=77&somethingElse=string
Let the URL class do the heavy lifting for you:
const input = 'http://localhost:8080/type/3259/?filters=901&numberType=77';
const parsed = new URL(input);
console.log(parsed.searchParams.get('numberType'));

Add parameters to url with onSubmit using a Javascript function

I want to add html parameters to the url with onsubmit. I have 2 forms(1 GET, 1 POST), want to use 1 button to submit them both(Using the POST form button) When the submit button is pressed use onSubmit to call a javascript function, where parameters are "appended" to the url.
I was thinking about doing something like this:
function onSubmitForm() {
url = "localhost:8080/test/index.php?Title=document.getElementsByName('title')[0].value";
//I don't know how to actually call the url.
}
EDIT
I got what I wanted:
Appending form input value to action url as path
First, you have to concatenate the string's static and dynamic parts. Then, you can redirect.
function onSubmitForm() {
window.location = "localhost:8080/test/index.php?Title=" +
document.querySelector('title').textContent;
}
NOTES:
Only form fields have a .value property. If you are trying to get
the text within an element, you can use .textContent.
.getElementsByName() scans the entire document and makes a
collection of all the matching elements. That's wasteful when you
know you want only the first one and, in the case of <title>, there
is only ever going to be one of those in a document anyway. Use
.querySelector() to locate just the first matching element.
ES6
NOTES :
Don't forget to use Babel for converting your code in ES5.
I purpose to you this solution :
function onSubmitForm() {
window.location = `localhost:8080/test/index.php? Title=${document.querySelector('title').textContent}`
}
This way of doing with backtick is even simpler than in ES5, let me explain, before we had to concatenate with the sign + ourVariable + the continuation of our string of character.
Here we have more of that. And we can write on several lines as well.
Then ${} is used to pass a variable inside
Documentation if you want : Literal template string

How to populate currency symbols in html 5 input element

I have the following html Input element:
<input size=6 type="text" id="prd_price" title="prd_price" name="prd_price" >
I want Currency Symbol ман for "Azerbaijani manat
" to be saved in the database. I would like to populate this as the symbol inside HTML Input element and perhaps concatenate with the price of a product. But when I populate the Input Element dynamically with the UTF-8 Code, it remains in the code form and does not become the Currency Symbol it is suppose to become.
Anyone knows what am I missing here...
The UTF-8 encoding can represent the complete Unicode catalogue (in fact, the letter U in the acronym comes from Unicode) so you don't need HTML entities in the first place. Such entities are only necessary if have characters that your current encoding cannot handle, which isn't the case here.
If you absolutely need to use those HTML entities (e.g., you consume a third-party data feed you cannot tweak) you need to realise that they only make sense in HTML context. A fairly common error in jQuery is to use .text() where you should really be using .html().
In this precise situation you have an <input> element so you cannot use either. Your only choice is .val(). However, since an <input> cannot contain HTML at all everything you feed .val() with will be eventually handled as plain text.
A little trick you can use is to create a detached node so you can use .html() to populate it with HTML and .text() to extract the plain text representation:
var $input = $("#prd_price");
// Original string "&#1084 ;&#1072 ;&#1085 ;" fixed:
var symbols = "ман"
var plainText = $("<span></span>").html(symbols).text()
$input.val(plainText);
... will render as:
ман
Demo
First of all I got the UTF-8 Code for Azerbaijani manat ман which is able to be run in javascript from "https://r12a.github.io/apps/conversion/". In this case it came up to be \u043C\u0430\u043D. Then I ran it up with the following code to get it display inside the input element using javascript:
var x = "\u043C\u0430\u043D";
var r = /\\u([\d\w]{4})/gi;
x = x.replace(r, function (match, grp) {
return String.fromCharCode(parseInt(grp, 16)); } );
x = unescape(x);
console.log(x);

D3.js Messing Up URL "%20" space character

I'm using D3 for listing a number of people along with there photos. We have there photos stored via a URL and I have that URL coming through as a field in the data. Every 10 seconds, I am calling an update function that updates the data in case new people get added or removed to/from the list.
I'm using the encodedURIComponent to encode the incoming url because some photos are store with spaces and some are not. This function is doing it's job. The issue seems to be happening when I append the url and the dynamic fileName together.
It works fine for most data elements, but on a few it screws my URL up. It only occurs on transition. The error will be something like this:
GET http://myUrl/images/employees/firstName%20LastNamepng
In this case, it removed the "." before the png. Here's another case:
GET http://myUrl/images/employees/firstName%6.279540991999999lastName.png
In this case, it came up with some random # to replace the 20%.
During the transition, I'm setting the attr to this:
"xlink:href": function (d) {
return "http://myURL/images/employees/" + d.encodedUrl;
}
Any idea??

How do I auto-populate a text field from URL Parameter using Javascript

This page (http://forums.iis.net/t/1153336.aspx) explains how to do exactly what I am wanting to do, except due to the limitations of our system I only get to enter javascript to pull this information into the textbox. Can someone explain how I can use a parameter in a URL to auto fill a textbox?
You can use location.search to access the url query and inject it into your text value
If your url is /page.htm?x=y, you can use the following code to set the value of a text field. This post tells you how to grab values from the query string
// See the link above for getUrlParams
var params = getUrlParams();
document.getElementById('myTextFieldId').value = params.x;
Notice that the example you've linked to suffers from a http://en.wikipedia.org/wiki/Cross-site_scripting vulnerability. To avoid that, you must escape the HTML before you output it on the screen
You should be able to do something similar using windows.location in js
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
You can easily use the answer of this question to get parameters from the URL using JavaScript. Then set the value of your textboxes like this:
this.form.elements["element_name"].value = 'Some Value';
If you want a quick solution, you might be interested in using this code snippet (inspiration taken from here, but modified by myself):
function getURLParameter(e) {
return decodeURI((new RegExp(e + "=(.+?)(&|$)").exec(location.search) || [, ""])[1]);
}
if (getURLParameter("inputKey") === "") {
console.log("No URL param value found.");
} else {
document.getElementById("inputBox").value = getURLParameter("inputkey");
}
Let's say that your url is example.com?inputKey=hello world. If so, using the above code will fill in the input with the ID of "inputBox" with the phrase "Hello world". If the URL was just example.com, it wouldn't prefill the box, and instead just act as though there was nothing (show the placeholder etc).

Categories

Resources