detect for empty field in angularJS - javascript

I'm getting json data with a bunch of spaces as strings like this:
{
appNumber: " "
}
but at times i get this back
{
appNumber: "123456"
}
I want to be able to detect when it doesnt have any numerical value in it and display a dash instead
so in my controller i have:
$scope.appNumber = function() {
var appNumber = $scope.appNumber.trim();
if (!appNumber) {
return "-";
}
return $scope.appNumber;
};
in my HTML:
<div ng-bind="appNumber()"></div>

You are calling trim on the current scope function. change the name of your variable you want to trim
To return appNumber if it is a number or '-' try below
$scope.appNumber = function() {
$scope.str = "12312";
var x = + $scope.str;
if (x.toString() === $scope.str) {
return $scope.str;
}
return '-';
};
Working fiddle

Related

javascript .data() cuts the string content by whitespace

So, I have this problem where I have a backwards-button in a webapplication. This is the javascript-code for the button:
function getPrevFunction()
{
localDBSelect("prevViews", function (prevViews)
{
if (prevViews)
{
var prevViewObject = $.parseJSON(prevViews);
var prevViewArray = prevViewObject['funcObjects'];
if (prevViewArray.length > 1)
{
var prevArrayIndex = prevViewArray.length - 2;
var actArrayIndex = prevViewArray.length - 1;
var prevFuncObject = prevViewArray[prevArrayIndex];
var prevFunc = prevFuncObject['function'];
var prevConfig = prevFuncObject['config'];
var inData = prevFuncObject['inData'];
prevViewArray.splice(actArrayIndex, 1);
if (inData !== "")
{
if (prevFunc !== "getGuiSiteList")
{
inData = "<div data-param=" + JSON.stringify(inData) + ">";
}
$('#fieldcontain')[prevFunc](inData, prevConfig);
}
else {
$('#fieldcontain')[prevFunc](prevConfig);
}
if (prevViewArray.length === 1)
{
setVisibilityForBackBtn(false); //If last..
}
prevViewObject['funcObjects'] = prevViewArray;
localDBInsert("prevViews", JSON.stringify(prevViewObject));
}
else {
setVisibilityForBackBtn(false);
}
$('#subcontainer').html("");
if(!$('#fieldcontain').is(":visible"))
{
$('#fieldcontain').show();
}
}
});
}
My problem is that I don't always get the entire content of the json-object. Eg; the json, at the beginning it looks like this:
input = {site: "GAV", location: "EG", set: "INVENTORY", binnum: "B01 T09"}
but after I have tried to fetch the json that is being passed as a data/attribute with an html-element like so:
var input = $(inData).data("param");
the value I recieve looks as follows:
input = "{"site":"GAV","location":"EG","set":"INVENTORY","binnum":"B01"
As you can se it has by some reason cut off all the characters after the whitespace, despite nothing happens between the fact that the last functions is added to the list, and that function is then called again, too be able to go backwards in the application.
I do realize that my explanation is messy and probably hard to understand, but this is the best that I can explain it.
I can provide more code if necessary.
So, I do need the entire json for the getPrevFunction (it is passed as "prevViews")
Use encodeURIComponent() and decodeURIComponent() like below
Setting the data
inData = "<div data-param=" + encodeURIComponent(JSON.stringify(inData)) + ">";
Getting the data
var input = JSON.parse(decodeURIComponent($(testDv).data('param')));
Now there will be no cuttings in the object due to whitespace.

Matching a string to an array

I need your your help,
For some strange reason, when my var str is set to "OTHER-REQUEST-ASFA" the matched key comes back as "ASF" as opposed to "ASFA"
How can I get the returned output key of "ASFA" when my str is "OTHER-REQUEST-ASFA"
function test() {
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
for (var key in filenames) {
if (str.indexOf(key) != -1) { alert(filenames[key]) }
}
}
You could switch from
str.indexOf(key)
to
key.indexOf(str)
function test() {
var str = "OTHER-REQUEST-ASFA",
filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
},
key;
for (key in filenames) {
if (key.indexOf(str) != -1) {
console.log(filenames[key]);
}
}
}
test();
To answer why it's not working as you want...
You've got:
str.indexOf(key)
This checks for the first instance of key in str.
So in your loop, key first equals OTHER-REQUEST-ASF which is part of OTHER-REQUEST-ASFA, so the condition is true.
However, to do what you want to do, if you know the pattern is always going to be OTHER-REQUEST-XYZ, the easiest way is to use split():
str.split('-')[2]
will always return the last section after the last -
cause "OTHER-REQUEST-ASFA".indexOf("OTHER-REQUEST-ASF") will not return -1, so it will show "ASF"
You can also use static method Object.keys() to abtain array of keys
var test = () =>{
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
Object.keys(filenames).forEach(x => {
if ( x.indexOf(str) !== -1)
console.log(filenames[str]);
});
}
test();

Javascript string variable to link

I'm making a chrome extension and I want to convert my javascript string variable into a clickable link. This is what my code does right now,
var regex = /[\w]+[\/]+[\w]+#(?:\d*\.)?\d+/g;
This finds a format on a page e.g. stack/overflow#12453. I convert the regex into a string with this function
function objectToString(object) {
var stringify = "";
for (var property in object) {
stringify += object[property] + '<br>';
}
return stringify;
}
What i want to do is to make that string into a clickable link. So if there are 5 links on a page, each of the strings returned would be a clickable link to a href. Is this possible? I would gladly appreciate any help.
Try this :
var obj = new Object();
obj.link1 = "www.google.com";
obj.link2 = "www.msn.com";
$().ready(function () {
$.each(objectToString(obj).split(','), function (i) {
$("ul").append("<li>" + objectToString(obj).split(',')[i] + "</li>");
});
});
function objectToString(object) {
var stringify = "";
for (var property in object) {
stringify += object[property] + ",";
}
stringify = stringify.slice(0, stringify.length - 1);
return stringify;
}
Jsfiddle : http://jsfiddle.net/u4hghL9c/

Avoid using dangerouslySetInnerHTML when wrapping HTML in React.js

I have this functionality for highlighting certain characters in the HTML of my component:
highlightQuery() {
// will output the text response from the Model, but also highlight relevant words if they match the search query
// that the user input
let input = this.props.model.get('value');
if(!this.state.hasMatch){
return input;
}
let query = this.props.matched.query,
index = this.props.model.get('searchIndexes')[this.props.matched.index];
const replaceBetween = (str, start, end, what) => {
return str.substring(0, start) + what + str.substring(start + end);
};
let ret = replaceBetween(input, index, query.length, `<span class='highlighted'>${query}</span>`);
return ret;
},
render() {
return (
<span dangerouslySetInnerHTML={ {__html: this.highlightQuery()} }></span>
);
}
So as you can see, if there's no match in this component's value then just return the input contents, else, wrap the matched text in a <span />.
What I'm after, is to avoid using dangerouslySetInnerHTML. Is this possible?
I'm not sure this will perfectly answer your question but I would do this to avoid dangerouslySetInnerHTML.
render() {
highlightQuery() {
let input = this.props.model.get('value');
if(!this.state.hasMatch){
return input;
}
let query = this.props.matched.query,
index = this.props.model.get('searchIndexes')[this.props.matched.index];
const replaceBetween = (str, start, end, what) => {
return str.substring(0, start) + what + str.substring(start + end);
};
let ret = replaceBetween(input, index, query.length, `<span class='highlighted'>${query}</span>`);
return ret;
}
var mycontent = highlightQuery();
return (
<span> {mycontent} </span>
);
}
hope it helps
Edit: I think I understand what you've meant now but in my opinion it doens't change the strategy, you work inside the render, choose your content and render it. (or maybe I still don't get it.. =p)
Is there any reason highlightQuery cannot return a react element?
highlightQuery(input,query, index) {
// will output the text response from the Model, but also highlight relevant words if they match the search query
// that the user input
var before = input.substring(0, index);
var after = input.substring(index + query.length);
return <span>{before}<span class='highlighted'>{query}</span>{after}</span>;
},
render() {
var input = this.props.model.get('value');
var query = this.props.matched.query;
var index = this.props.model.get('searchIndexes')[this.props.matched.index];
if(!this.state.hasMatch){
return <span>{input}</span>;
} else {
return highlightQuery(input, query, index);
}
}

Parse config string into javascript/JSON [duplicate]

This question already has answers here:
javascript parser for a string which contains .ini data
(4 answers)
Closed 10 years ago.
I have a textarea where the user edits configurations. It is formatted like this:
foo = 'value'
bar = 2.1
john = false
Values can be false, true, floats or strings (no functions). I need to regexp this string to create something like:
{
foo: 'value',
bar: 2.1,
john: false
}
Is there a library or something for this?
I took this answer which should be a good beginning for your request, and added some further rules to handle the different data types, maybe this helps:
var data ="foo = 'value'";
data +="\n" + "bar = 2.1";
data += "\n" + "john = false";
function JSONFY(data){
var regex = {
section: /^\s*\[\s*([^\]]*)\s*\]\s*$/,
param: /^\s*([\w\.\-\_]+)\s*=\s*(.*?)\s*$/,
comment: /^\s*;.*$/
};
var value = {};
var lines = data.split(/\r\n|\r|\n/);
var section = null;
function handleSection(sec) {
var isFloat = /^(?:[1-9]\d*|0)?(?:\.\d+)?$/;
if(sec.match(isFloat)) {
return parseFloat(sec);
} else if(sec=='true') {
return true;
} else if(sec=='false') {
return false;
}
return sec.replace(/^['"]/,'').replace(/['"]$/,'');
}
lines.forEach(function(line){
if(regex.comment.test(line)){
return;
}else if(regex.param.test(line)){
var match = line.match(regex.param);
if(section){
value[section][match[1]] = match[2];
}else{
value[match[1]] = handleSection(match[2]);
}
}else if(regex.section.test(line)){
var match = line.match(regex.section);
value[match[1]] = {};
section = match[1];
}else if(line.length == 0 && section){
section = null;
};
});
return value;
}
console.log(JSONFY(data));
Here is the fiddle to test.
Depending on how much you can trust the input data, you can always write a simple function utilising code like the following (uses jQuery for simplicity's sake):
var lines = $('textarea').val().split('\n');
var output = '{';
$(lines).each(function(l){
output += '\n\t' + lines[l].replace(/(\w+)\s=\s(.*)/, '$1: $2,');
});
output = output.substring(0, output.length - 1);
output += '\n}';
$('textarea').val(output);
The main point here is that you will want to tweak the regex depending on how strict you want to be (i.e. allow whitespace to be optional with a ? after the \s or make sure the values are a specific format.

Categories