Testing against a string/object - javascript

I have a JSON-encoded PHP array:
<script>
var registeredEmails = <?php echo(json_encode($emails)); ?>;
</script>
To check that this works, I do this:
console.log(registeredEmails);
// this outputs: ["john#domain.com", "mary#domain.com"]
And now I would like to iterate through that JSON and test a certain string against all the strings it contains.
for (var email in registeredEmails) {
if (registeredEmails.hasOwnProperty(email)) {
var duplicate = registeredEmails[email];
console.log(duplicate + ' is typeof: ' + typeof(duplicate));
// this outputs: john#domain.com is typeof: string
// $(this).val() is a string from somewhere else
if (duplicate.test($(this).val())) {
// we found a match
};
}
}
As I understand it, the test() method tests for matches on strings. I've tested to make sure that my variable duplicate is a string, but apparently it's still an object. I'm given the following JS error:
Uncaught TypeError: Object john#domain.com has no method 'test'
Why is that?

test() is a method of the RegEx object, not String.
Your best bet would probably be to use String.search() instead. You could also probably use String.indexOf() if you're not trying to use Regular Expression matching.

Although you are using json_encode your console output looks like an array to me. If that is the case then maybe you can use the following:
var found = find_match( registeredEmails, $(this).val() );
if( found ) {
// found a match
}
function find_match(array, string) {
for( var i = 0, len = array.length; i < len ; i++ ) {
if( array[i].indexOf( string ) > -1 ) return true;
}
return false;
}​
Fiddle here

Related

Building JavaScript Array in C#, apostrophes changing

I have done this to build JavaScript Arrays from int, double and string lists.
public string listToJsArray<T>(List<T> cslist)
{
bool numeric = true;
if(
!(typeof(T)==typeof(int)
|| typeof(T) == typeof(string)
|| typeof(T) == typeof(double))
)
{
throw (new ArgumentException(message: "Only int, double and string are supported"));
}
if(typeof(T)==typeof(string))
{
numeric = false;
}
string JsArray = "[";
for(int i=0;i<cslist.Count;i++)
{
string dataWithSurrendings = cslist[i].ToString();
if(!numeric)
{
dataWithSurrendings = "'" + cslist[i].ToString() + "'";
}
if(i !=0)
{
dataWithSurrendings = "," + dataWithSurrendings;
}
if(i +1==cslist.Count)
{
dataWithSurrendings = dataWithSurrendings + "]";
}
JsArray += dataWithSurrendings;
}
return JsArray;
}
My problem is when a list of strings is passed, apostrophes turn into '.
for example, a list of {"1","2","3","4","5","6","7"} becomes this:
['1','2','3','4','1','6','7']
What modification is needed in this function, to return a correct array in JavaScript?
None of solutions did solve the problem. With JsonConvert I get almost same result. The problem is the single or double quote in View editor have not the same encoding as CS string.
I'm assuming that you are doing this to drop into a webpage somewhere, something like:
<script>
#{
var output = listToJsArray(Model.SomeList);
}
var myArray = #Html.Raw(output);
// some Javascript using that array
</script>
Don't waste your time trying to do it yourself. It's a pain and you are reinventing the wheel. JSON is valid Javascript and a serialization of an array into JSON is absolutely identical to a Javascript array literal. So use Javascript. JSON.Net is really useful here:
<script>
#{
var output = Newtonsoft.Json.JsonConvert.SerializeObject(Model.SomeList);
}
var myArray = #Html.Raw(output);
// some Javascript using that array
</script>
The serializer will handle all the annoying escaping, special characters and edge cases for you.

AngularJS bind and replace text [duplicate]

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.

Validate variable javascript

I need to validate some user input with javascript. I need to check that their entry (value) is of the correct type (type).
I need my regex pattern to make sure values only contain numbers and nothing else, except measurment types can also contain decimal points.
What is the correct way to do this? My way seems like it may be, but i am guessing. In any case, something is wrong with my regular expression patterns as it is throwing the error stated in the code comment.
Here is my code:
function validateInput(value, type) {
console.log(value);
if(type === "Integer"){
var patt = new RegExp("^\D", i);
}
else if(type === "Measurement"){
var patt = new RegExp("^\D", i); //Uncaught SyntaxError: Invalid flags supplied to RegExp constructor '2'
}
else{
return true;
}
if(patt.test(value)){
return false;
}
else{
return true;
}
}
function sendObs() {
RID = $("#oid").val();
console.log(RID);
var children = $("#abc").children();
var xmlString = "<root><rid>" + RID + "</rid>";
for(i=0; i < children.length; i++){
var value = children[i].children[0].value;
var type = children[i].children[0].id;
var validationResult = validateInput(value, type);
if(!validationResult){ //calling the validation method here
alert("invalid entry");
return;
}
var code = children[i].children[0].className;
xmlString += '<question><code>' + code + '</code><value>' + value + '</value></question>'
}
xmlString +='</root>'
console.log(xmlString);
data = $.parseXML(xmlString);
console.log(data);
//send it here
}
Instead of using regular expressions, you could just call parseInt() and parseFloat().
On top of converting your strings to workable numbers, both functions return NaN if the input is invalid.
number = parseFloat(string)
if (isNaN(number)) {
# `string` is invalid
}

Cannot get value using Regex

Code
if(x.substr(0,4)=='init') {
output += 'Initialised<br>';
var rgx = /^\[typ-$\]/i;
if (rgx.test(x))output+='Type given<br>';
else output+='No type: '+x+'<br>';
}
container.append(output);
What I'm trying to do
I'm simulating a command-line terminal for a website. One command is init which carries the parameter type. The parameter is set by typing:
init [typ-Foo]
I'm trying to then get the value of the type parameter (in this case, Foo).
What's happening
I'm failing to get the value at all. It's returning No Type: init [typ-Foo] which is what the function returns when no value is found. I haven't played about with Regex before so I'm sure that my command is incorrect but I'm unable to make it work!
var result = /\[typ-([^\]]+)]/.exec( userInput );
if (result){
console.log("type: " + result[1]);
}
else {
// no type
}
If result is null, then there's no type. If it isn't, the type is in result[1]
This regex looks a little complicated because we're using [ and ]s in their special, regex meaning and also as literal characters.
Try something more like this:
var rgx = /^init \[typ-(.*)\]$/i;
m = x.match(rgx);
if ( m != null ) {
output += 'Initialised<br>';
output+='Type given<br>';
output+='Argument: ' + m[1]; // note this is the "Foo" value
}
else {
output+='No type: '+x+'<br>';
}
container.append(output);
This pattern should do the trick.
var rgx = /^init\s\[typ\-([^\]]+)\]/;
This is what happens.
From Regexper.com

Regex to check if http or https exists in the string

So i have this code:
function validateText(str)
{
var tarea = str;
var tarea_regex = /^(http|https)/;
if(tarea_regex.test(String(tarea).toLowerCase()) == true)
{
$('#textVal').val('');
}
}
This works perfectly for this:
https://hello.com
http://hello.com
but not for:
this is a website http://hello.com asdasd asdasdas
tried doing some reading but i dont where to place * ? since they will check the expression anywhere on the string according here -> http://www.regular-expressions.info/reference.html
thank you
From the looks of it, you're just checking if http or https exists in the string. Regular expressions are a bit overkill for that purpose. Try this simple code using indexOf:
function validateText(str)
{
var tarea = str;
if (tarea.indexOf("http://") == 0 || tarea.indexOf("https://") == 0) {
// do something here
}
}
Try this:
function validateText(string) {
if(/(http(s?)):\/\//i.test(string)) {
// do something here
}
}
The ^ in the beginning matches the start of the string. Just remove it.
var tarea_regex = /^(http|https)/;
should be
var tarea_regex = /(http|https)/;
((http(s?))\://))
Plenty of ideas here : http://regexlib.com/Search.aspx?k=URL&AspxAutoDetectCookieSupport=1
Have you tried using a word break instead of the start-of-line character?
var tarea_regex = /\b(http|https)/;
It seems to do what I think you want. See here: http://jsfiddle.net/BejGd/

Categories

Resources