I have a table listing values pulled from a database, I then gather up these values and save them into an array to be sent back to the database (with JSON) I'm using
$('#ing_table tr').each(function(row, tr){
ingredients[row] = {
"ing" : $(tr).find('input:eq(0)').val(),
"amt" : $(tr).find('input:eq(1)').val(),
"meas" : $(tr).find('option:selected').text()
};
});
to get this info. Generally everything works great except that a few of the strings that occasionally populate the 'ing' row have quotes (") which mess things up. I tried this:
$('#ing_table tr').each(function(row, tr){
ingredients[row] = {
"ing" : $(tr).find('input:eq(0)').val().replace('"', ' '),
"amt" : $(tr).find('input:eq(1)').val(),
"meas" : $(tr).find('option:selected').text()
};
});
but I get a 'cannot call method 'replace' of undefined'
Note: The above code is found in the function stroreIng() which returns ingredients. I used:
var recIng = storeIng();
recIng = $.toJSON(recIng);
this is where it added \\ before the " in the JSON
Any help would be appreciated
It seems that there simply isn't any input present for some rows. And in case of empty selectors val() returns undefined:
$().val() == undefined //true
so your replace method fails in such cases. You should use something like this:
$('#ing_table tr').each(function(row, tr){
ingredients[row] = {
"ing" : ($(tr).find('input:eq(0)').val() || "").replace('"', ' '),
"amt" : $(tr).find('input:eq(1)').val(),
"meas" : $(tr).find('option:selected').text()
};
});
I was unable to get the replace() method to work here, but I went to the php page and was able to use str_replace() to remove the escaped quote. Now everything works fine. Thanks for your help!
Related
I'm new to AngularJS and trying to create a simple app that will allow me to upload files to my Laravel driven website. I want the form to show me the preview of what the uploaded item will look like. So I am using ng-model to achieve this and I have stumbled upon the following:
I have an input with some basic bootstrap stylings and I am using custom brackets for AngularJS templating (because as I mentioned, I am using Laravel with its blading system). And I need to remove spaces from the input (as I type it) and replace them with dashes:
<div class="form-group"><input type="text" plaeholder="Title" name="title" class="form-control" ng-model="gnTitle" /></div>
And then I have this:
<a ng-href="/art/[[gnTitle | spaceless]]" target="_blank">[[gnTitle | lowercase]]</a>
And my app.js looks like this:
var app = angular.module('neoperdition',[]);
app.config(function($interpolateProvider){
$interpolateProvider.startSymbol('[[').endSymbol(']]');
});
app.filter('spaceless',function(){
return function(input){
input.replace(' ','-');
}
});
I get the following error:
TypeError: Cannot read property 'replace' of undefined
I understand that I need to define the value before I filter it, but I'm not sure where to define it exactly. And also, if I define it, I don't want it to change my placeholder.
There are few things missing in your filter. First of all you need to return new string. Secondary, regular expression is not correct, you should use global modifier in order to replace all space characters. Finally you also need to check if the string is defined, because initially model value can be undefined, so .replace on undefined will throw error.
All together:
app.filter('spaceless',function() {
return function(input) {
if (input) {
return input.replace(/\s+/g, '-');
}
}
});
Demo: http://plnkr.co/edit/5Rd1SLjvNI18MDpSEP0a?p=preview
Bravi just try this filter
for eaxample {{X | replaceSpaceToDash}}
app.filter('replaceSpaceToDash', function(){
var replaceSpaceToDash= function( input ){
var words = input.split( ' ' );
for ( var i = 0, len = words.length; i < len; i++ )
words[i] = words[i].charAt( 0 ) + words[i].slice( 1 );
return words.join( '-' );
};
return replaceSpaceToDash;
});
First, you have to inject your filter in you module by adding it's name to the array :
var app = angular.module('neoperdition',['spaceless']);
Secondly, the function of the filter have to return something. The String.prototype.replace() return a new String. so you have to return it :
app.filter('spaceless',function(){
return function(input){
return input.replace(' ','-');
}
});
Edit: dfsq's answer being a lot more accurate than mine.
I have a JSONObj which contains various elements. I want to perform a Regex (or some type of search) on the text data of this object and find various strings, and replace them with some other text, for example, I want to replace the string "content" with the string "http://www.example.com/content" :
description = jsonObj.channel.item[jsonCounter].description.replace(/\/content/g, "http://www.example.com/content");
This works perfectly, but I want to first check if a string is present, and then replace it, I tried :
if (holder.indexOf("about-us") !== -1) {
description = jsonObj.channel.item[jsonCounter].description.replace(/\/about-us/g, "http://www.example.com/about-us");
} else {
description = jsonObj.channel.item[jsonCounter].description.replace(/\/content/g, "http://www.example.com/content");
}
But this doesn't seem to work. Can anyone help me solve this issue?
As you said :
holder is my JSONObj converted to a string :
var holder = jsonObj.toString();
var holderJSON = {url:"http://www.example.com/about-us"}
alert(holderJSON.toString()); **// this returns [Object Object]**
if (holder.indexOf("about-us") !== -1) **// is never true.**
Hope this helps!!
Hey all im not every good with regexp i was hoping someone could help.
ok so this is the sting "KEY FOUND! [ 57:09:91:40:32:11:00:77:16:80:34:40:91 ]"
And i need to pull "57:09:91:40:32:11:00:77:16:80:34:40:91", now this key can be meany length not just as written here and with or with out the ":"
now the second sting i would like to test and extract is: "[00:00:09] Tested 853 keys (got 179387 IVs)", i would like to pull "00:00:09" and "853" and "179387".
this would be the raw string http://regexr.com?31pcu or http://pastebin.com/eRbnwqn7
this is what im doing now.
var pass = new RegExp('KEY FOUND\!')
var tested = new RegExp('Tested')
var fail = new RegExp('\Failed. Next try with ([0-9]+) IVs')
var data="Look at the link i added"
if (tested.test(data)) {
self.emit('update', mac, {
'keys' : data.split('Tested ')[1].split(' keys ')[0],
'ivs' : data.split('got ')[1].split(' IVs')[0]
});
} else if (pass.test(data)) {
var key = data.split('KEY FOUND! [')[1].split(' ]')[0].split(':').join('');
} else if (fail.test(data)) {
console.log(data);
}
thanks all
Edit:
I have added more the the question to help with the answer
If it is always surrounded by [] then it is simple:
\[([\s\S]*)\]
This will match any characters enclosed by [].
See it in action here.
I run next code and I miss somthing, for me it seem OK :
window.onload = TitleFieldInit;
function TitleFieldInit() {
var str = document.cookie.split("=")[1];
var space = str.split("=")[1];
space = space.split(";")[0];
alert(space);
// while( space.indexOf('%20' )+1) space = space.replace(/%20/,' ');
if (document.cookie != "") {
document.getElementById("TitleField").innerHTML = "Your Title is : " + space;
}
}
and I got err in FireFox rror"space is undefined" why ?
In chrome "Uncaught TypeError:Cannot call method'split' of Undefined"
Thx for helping.
This code will never work for any input.
str is a already part of result of split by =, i.e. it contains no = symbols.
Then you split that result again by =, which of course will return you one-element array and str.split("=")[1] will always be undefined.
Looks like you're trying to read cookie value... but second .split("=") is not needed at all.
Ah, and you got different results in different browsers, cause they contain different data in their cookies.
PS: Instead of while( space.indexOf('%20' )+1) space = space.replace(/%20/,' '); you may write space = space.replace(/%20/g,' '); to replace all of them at once.
A user of my HTML 5 application can enter his name in a form, and this name will be displayed elsewhere. More specifically, it will become the innerHTML of some HTML element.
The problem is that this can be exploited if one enters valid HTML markup in the form, i.e. some sort of HTML injection, if you will.
The user's name is only stored and displayed on the client side so in the end the user himself is the only one who is affected, but it's still sloppy.
Is there a way to escape a string before I put it in an elements innerHTML in Dojo? I guess that Dojo at one point did in fact have such a function (dojo.string.escape()) but it doesn't exist in version 1.7.
Thanks.
dojox.html.entities.encode(myString);
Dojo has the module dojox/html/entities for HTML escaping. Unfortunately, the official documentation still provides only pre-1.7, non-AMD example.
Here is an example how to use that module with AMD:
var str = "<strong>some text</strong>"
require(['dojox/html/entities'], function(entities) {
var escaped = entities.encode(str)
console.log(escaped)
})
Output:
<strong>some text</strong>
As of Dojo 1.10, the escape function is still part of the string module.
http://dojotoolkit.org/api/?qs=1.10/dojo/string
Here's how you can use it as a simple template system.
require([
'dojo/string'
], function(
string
){
var template = '<h1>${title}</h1>';
var message = {title: 'Hello World!<script>alert("Doing something naughty here...")</script>'}
var html = string.substitute(
template
, message
, string.escape
);
});
I tried to find out how other libraries implement this function and I stole the idea of the following from MooTools:
var property = (document.createElement('div').textContent == null) ? 'innerText': 'textContent';
elem[property] = "<" + "script" + ">" + "alert('a');" + "</" + "script" + ">";
So according to MooTools there is either the innerText or the textContent property which can escape HTML.
Check this example of dojo.replace:
require(["dojo/_base/lang"], function(lang){
function safeReplace(tmpl, dict){
// convert dict to a function, if needed
var fn = lang.isFunction(dict) ? dict : function(_, name){
return lang.getObject(name, false, dict);
};
// perform the substitution
return lang.replace(tmpl, function(_, name){
if(name.charAt(0) == '!'){
// no escaping
return fn(_, name.slice(1));
}
// escape
return fn(_, name).
replace(/&/g, "&").
replace(/</g, "<").
replace(/>/g, ">").
replace(/"/g, """);
});
}
// that is how we use it:
var output = safeReplace("<div>{0}</div",
["<script>alert('Let\' break stuff!');</script>"]
);
});
Source: http://dojotoolkit.org/reference-guide/1.7/dojo/replace.html#escaping-substitutions