javascript regular expression to replace string - regex

I have unspecified number of html inputs:
<input id="ageInput" />
<input id="nameInput" />
...
and having the following string which is built based on inputs:
s = "{ 'age': '{ageInput}', 'name': '{nameInput}'}"
how could I use regular expression to replace the above string to reflect the current inputs values like this:
s = "{ 'age': " + $('#ageInput').val() + ", 'name': " + $('#nameInput').val() + " }"

Answering your original question, use replace method of string , which accepts function as parameter:
s = s.replace(/\{([^{}]+)\}/g, function (match, g1) {
return $("#" + g1).val()
})
But I would rather use JSON.stringify:
var s = "{ 'age': '{ageInput}', 'name': '{nameInput}'}"
, controlMap = JSON.parse(s)
, data = {}
for(var i in controlMap) {
data[i] = $(controlMap[i]).val()
}
var str = JSON.stringify(data)

Related

Google Chart google.visualization.arrayToDataTable: How can I pass a formatted string

I have created the following string in PHP
["Month", "Points", {role: "style"}, "Goal", {role: "annotation"}],
["JAN", 3, "#4a7dae", 6.5, ""],
["FEB", 2, "#4a7dae", 6.5, ""],
["MAR", 3, "#4a7dae", 6.5, ""],
["APR", 1, "#4a7dae", 6.5, ""],
["MAY", 2, "#4a7dae", 6.5, ""],
["JUN", 1, "#4a7dae", 6.5, "Goal (6.5)"]
and want the same to use in Google Chart data
The above string I have grabbed in a JavaScript variable (str_data) and tried like this
var data = google.visualization.arrayToDataTable([str_data]);
but getting the following error:
jsapi_compiled_default_module.js:23 Uncaught (in promise) Error: First row is not an array.
at gvjs_rba (jsapi_compiled_default_module.js:23)
at Object.gvjs_Tl [as arrayToDataTable] (jsapi_compiled_default_module.js:25)
at prev_year_chart_callback_function (evd-all.js?ver=1.0:212)
UPDATE (PHP code)
The following code runs inside a loop and creates one row at a time.
$model_str = '["Month", "Points", {role: "style"}, "Goal", {role: "annotation"}],';
if ( $row_index === count( $assoc_array ) - 1 ) {
$model_str .= '["' . $unix_month_start_formatted . '", ' . $assoc_array[ $key ] . ', "#4a7dae", ' . $prior_season_goal_point . ', "Goal (' . $prior_season_goal_point . ')"],';
} else {
$model_str .= '["' . $unix_month_start_formatted . '", ' . $assoc_array[ $key ] . ', "#4a7dae", ' . $prior_season_goal_point . ', ""],';
}
instead of trying to pass json as a string
build the json in php, then pass the encoded json as a string
// create column headings
$model_str = [];
$columns = [];
$columns[] = "Month";
$columns[] = "Points";
$columns[] = ["role" => "style"];
$columns[] = "Goal";
$columns[] = ["role" => "annotation"];
$model_str[] = $columns;
// create rows
$row = [];
if ( $row_index === count( $assoc_array ) - 1 ) {
$row[] = $unix_month_start_formatted;
$row[] = $assoc_array[$key];
$row[] = "#4a7dae";
$row[] = $prior_season_goal_point;
$row[] = "Goal (" . $prior_season_goal_point . ")";
} else {
$row[] = $unix_month_start_formatted;
$row[] = $assoc_array[$key];
$row[] = "#4a7dae";
$row[] = $prior_season_goal_point;
$row[] = "";
}
$model_str[] = $row;
// return json
echo json_encode($model_str);
then, assuming you're using ajax to get the data, set the type to json...
$.ajax({
url: '...',
dataType: 'json'
}).done(...

Search Marker Leaflet Map

I am working on an application with Django. There in this application, I am first using Django to create a database with points and extract a JSON file (It is called "markers.json"). Then, using this JSON file, I am creating markers on a map with Leaflet. When I finished entering all the points to the database they will be around 5000 thousand. So, I decided that it is a good idea to be able to search this markers with an input tag and a search button. I enter the "site_name" as input and when I click the "search" button the related marker should popup. However, always the same marker pops up and I don't know where I am doing wrong.
Could you please help me on that?
HTML PART
<input type="text" id="mast_find" name="mastName" placeholder="Search or masts...">
<button type="submit" id="mast_button">Search</button>
JAVASCRIPT PART
var streets = L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap',
subdomains: ['a', 'b', 'c']
}),
esri = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
}),
topo = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
maxZoom: 17,
attribution: 'Map data: © OpenStreetMap, SRTM | Map style: © OpenTopoMap (CC-BY-SA)'
});
var map = L.map( 'map', {
center: [20.0, 5.0],
minZoom: 2,
zoom: 2,
layers: [streets, esri, topo]
})
var baseMaps = {
"Streets": streets,
"Esri": esri,
"Topo": topo
};
$('.leaflet-control-attribution').hide()
L.control.scale().addTo(map);
L.control.layers(baseMaps).addTo(map);
var myURL = jQuery( 'script[src$="leaf.js"]' ).attr( 'src' ).replace( 'leaf.js', '' )
var myIcon = L.icon({
iconUrl: myURL + '/images/pin24.png',
iconRetinaUrl: myURL + '/images/pin48.png',
iconSize: [29, 24],
iconAnchor: [9, 21],
popupAnchor: [0, -14]
})
for ( var i=0; i < markers.length; ++i )
{
var deneme = [];
var meleme = L.marker( [markers[i].fields.latitude, markers[i].fields.longitude], {icon: myIcon} )
.bindPopup( "<b>" + "Mast name: " + "</b>" + markers[i].fields.site_name + "<b>" + "<br>" + "A: " + "</b>" + markers[i].fields.a_measured_height_lt + "<br>" + "<b>" + "k: " + "</b>" + markers[i].fields.k_measured_height_lt )
.addTo( map );
deneme.push(meleme);
document.getElementById("mast_button").onclick = mastFunct;
function mastFunct(){
var data = document.getElementById("mast_find");
for (var i=0; i < markers.length; ++i ){
var markerID = markers[i].fields.site_name;
if (markerID = data.value){
deneme[i].openPopup()
}
}
};
if (markerID = data.value){
should be
if (markerID == data.value){
the only issue that i see is this with the if (markerID = data.value){.
But you can try this alternative:
instead your for-loop:
map.eachLayer(function(marker){
if(marker.options){
var markerID = marker.options.site_name;
if (markerID == data.value){
marker.openPopup();
}
}
});
and add this to your marker creation:
L.marker([51.493782, -0.089951],{icon: myIcon, site_name: 'test'}).addTo(map)

Regex - Replace input and output as decimals only? [duplicate]

Anyone have a regex to strip lat/long from a string? such as:
ID: 39.825 -86.88333
To match one value
-?\d+\.\d+
For both values:
(-?\d+\.\d+)\ (-?\d+\.\d+)
And if the string always has this form:
"ID: 39.825 -86.88333".match(/^ID:\ (-?\d+\.\d+)\ (-?\d+\.\d+)$/)
var latlong = 'ID: 39.825 -86.88333';
var point = latlong.match( /-?\d+\.\d+/g );
//result: point = ['39.825', '-86.88333'];
function parseLatLong(str) {
var exp = /ID:\s([-+]?\d+\.\d+)\s+([-+]?\d+\.\d+)/;
return { lat: str.replace(exp, "$1"), long: str.replace(exp, "$2") };
}
function doSomething() {
var res = parseLatLong("ID: 39.825 -86.88333");
alert('Latitude is ' + res.lat + ", Longitude is " + res.long);
}

Writing a regex for an Express route which has a variable number of parameters

I'm building an API, and trying to allow the user to 'filter' the result set using any combination of parameters.
We have 2 cats, each with 4 properties: name, age, sex and color.
cat1 = {'name': 'Fred', 'age': '10', 'sex': 'male', 'color': 'white'}
cat2 = {'name': 'Alex', 'age': '10', 'sex': 'male', 'color': 'black'}
I'd like a single route to match any combination of the parameters the user chooses to apply to their search. For example, the route would match the following (as well as any other combination):
router.get('/name/:name/age/:age/sex/:sex/color/:color', ...){}
router.get('/name/:name/age/:age/sex/:sex', ...){}
router.get('/age/:age/color/:color', ...){}
Essentially, all parameters are optional.
I think regex is the best way to go - how can I do this?
A way to do this is to use a regular expression to parse the full URI and extract the search criteria. Criteria order is free.
To extract the value of a parameter, I use the following regular expression :
\/paramName\/([^\/]+)(\/|$)
Explanation
\/paramName\/ : Match the given parameter name between slashes
([^\/]+) : Match anything except a slash (This is our value)
(\/|$) : Ends with a slash or end of line
Here is a working JavaScript snippet :
/**
* Extract the value of a param inside a path
* Path format should match this pattern : /p1/p1value/p2/p2Value/pX/pXValue
* #param {string} path The path
* #param {string} param The param name
*/
function getParamValue(path, param) {
var re = new RegExp('\/'+ param + '\/([^\/]+)(\/|$)');
var matches = re.exec(path);
if(matches && matches.length) {
return matches[1];
}
}
// Define possible criteria
var criteria = ['name', 'age', 'sex', 'color', 'dummy'];
// Let's play with some sample paths
var paths = [
"/name/mcfly/age/42/sex/male/color/blue",
"/sex/male/name/color/blue/mcfly/age/42",
"/sex/male",
"/color/black/name/kitty"
];
// For each path, display criteria and associated values
paths.forEach(function(path) {
console.log("path=", path);
criteria.forEach(function(criterion) {
console.log(criterion + '=' + getParamValue(path, criterion));
});
console.log("------------------------");
});
In addition, here is a sample Express app :
utils.js
module.exports = {
getParamValue: function (path, param) {
var re = new RegExp('\/'+ param + '\/([^\/]+)(\/|$)');
var matches = re.exec(path);
if(matches && matches.length) {
return matches[1];
}
}
}
search-service.js
var utils = require('./utils');
module.exports = {
getSearchCriteria: function(path) {
var criteria = [];
['name', 'age', 'sex', 'color'].forEach(function(criterion) {
var value = utils.getParamValue(path, criterion);
if(value) {
criteria.push({"criterion": criterion, "value": value});
}
});
return criteria;
},
search: function(criteria) {
return "search using the following criteria", JSON.stringify(criteria, null, 2);
}
}
app.js
var express = require('express');
var app = express();
var searchService = require('./search-service');
var port = 7357;
app.get('/api/search/*', function(req, res, next) {
var criteria = searchService.getSearchCriteria(req.originalUrl);
var result = searchService.search(criteria);
res.send("<!doctype html><html><body><pre>" + result + "</pre></body></html>");
});
// start server
app.listen(port, function() {
console.log('Server listening on port %d', port);
});
Run node app then test some urls :
http://localhost:7357/api/search/name/mcfly/age/42/sex/male/color/blue
http://localhost:7357/api/search/sex/female/color/orange/name/judith/age/25
http://localhost:7357/api/search/color/green
and check page content

Match with multiple conditions in $OR

In MongoDB I have 2 conditions
First condition:
"\"userfullname\":{$regex : \"" + filtertext + "\", $options: 'i'}";
Second condition:
"\"email\":{$regex : \"" + filtertext + "\", $options: 'i'}";
I need to OR condition on this statement so what I did is:
matchquery = matchquery + "\"userfullname\":{$regex : \"" + filtertext + "\", $options: 'i'}"+["%OR:"]+"\"email\":{$regex : \"" + filtertext + "\", $options: 'i'}";
but of course that did not work. How can I achieve this?
Use the Or Operator & create it like this :
var condition1 =
"\"userfullname\":{$regex : \"" + filtertext + "\", $options: 'i'}";
var condition2 = "\"email\":{$regex : \"" + filtertext + "\", $options: 'i'}";
var matchquery = "{ \"$or\" : [ " + condition1 + "," + condition2 +" ]}"
Use the $or operator. You essentially want to create a query which has the form
var matchquery = {
'$or': [
{ 'userfullname': { '$regex': \filtertext\, '$options': 'i' } },
{ 'email': { '$regex': \filtertext\, '$options': 'i' } }
]
}
If filtertext is a variable then you can use RegExp constructor which creates a regular expression object for matching text with a pattern. For example:
var filtertext = "foo";
var rgx = new RegExp(filtertext, "i");
var matchquery = {
"$or": [
{ "userfullname": rgx },
{ "email": rgx }
]
};
To stringify the query, you could try:
var filtertext = "foo";
var rgx = new RegExp(filtertext, "i");
var matchquery = '{ "$or":[{ "userfullname": {"$regex": '+ rgx.toString() +'} },{ "email":{ "$regex": '+ rgx.toString() + '} }] } }';