Is it possible to split this string into two using css or another way?
<p>30/10/2018 16:10</p>
into
<p>30/10/2018</p>
<p>16:10</p>
because i have a string data from JSON API that return value like "30/10/2018 16:10" by using this code <p>{{creationDate}}</p>
but I needed it to display like this
30/10/2018
16:10
Did anyone get any idea for how to settle this case?
You can split the date with space character which will give you the the date in 0 index and the time in 1 index:
<p>{{creationDate.split(' ')[0]}}</p>
<p>{{creationDate.split(' ')[1]}}</p>
Use moment for date format
import moment from 'moment'
Vue.filter('formatDate', function(value) {
if (value) {
return moment(String(value)).format('MM/DD/YYYY')
}
}
Vue.filter('formatTime', function(value) {
if (value) {
return moment(String(value)).format('hh:mm')
}
}
<P>{{yourDateString | formatDate}}</P>
<P>{{yourDateString | formatTime}}</P>
You can use Javascript split function. Use space as separator.
Syntax: string.split(separator, limit)
Read more: https://www.w3schools.com/jsref/jsref_split.asp
let creationDate="30/10/2018 16:10";
creationDate=creationDate.split(' ');
const docum=document.getElementById("date");
docum.innerHTML='<p>'+creationDate[0]+'</p>'+'<p>'+creationDate[1]+'</p>';
<div id="date"></div>
Related
I'm a beginner in Typescript. I have a date range which I'm receiving as a string.
var range="7-01-2018 VS 5-01-2019";
It is hard coded right now just to explain you. But it will be in this string form only later also. I've to extract 2018 and store it in some variable, say startYear and also I've to extract 2019 and store it in endYear variable. So that later I can compare them and apply validations.
I tried using:
substring(start,end)
My code worked but the problem is that the string will change its length when a double digit date is selected. For eg:
7-01-2018 VS 25-01-2019 or
17-01-2018 VS 5-01-2019 or
27-01-2018 VS 25-01-2019
In these cases start and end will have different meanings. What should I do now. Please help me.
My method is:
myValidator() {
range="7-01-2018 VS 5-01-2019";
startYear=range.substring(5,8);
endYear=range.substring(18,21);
if(endYear<startYear) {
console.log("Invalid range");
}
}
Now I'm planning to use split(). And split the string into different parts and then write some logic with that. But the problem with split is that there's a VS in between. However for separator parameter i can give - symbol. Please correct me if I'm wrong.
you are right split will be good
myValidator() {
range="7-01-2018 VS 5-01-2019";
startYear=parseInt(range.split("VS")[0].split("-")[2])
endYear=parseInt(range.split("VS")[1].split("-")[2])
if(endYear<startYear) {
console.log("Invalid range");
}
}
All in one line
const [,startYear,endYear]=range.match(/.*-(\d{4}) VS .*-(\d{4})$/);
Using String.prototype.match
const range = '7-01-2018 VS 25-01-2019'
const [...range.matchAll(/\d{0,2}-\d{0,2}-(\d{0,4})/g)].map((date)=> date[1])
Using split, Date and reduce:
console.log("7-01-2018 VS 25-01-2019: ", checkRange("7-01-2018 VS 25-01-2019"));
console.log("7-01-2019 VS 25-01-2018: ", checkRange("7-01-2019 VS 25-01-2018"));
function checkRange(inputRange) {
const range = inputRange.split(" VS ");
const getYear = dateStr =>
new Date(dateStr.split("-").reverse().join("-")).getFullYear();
const years = range.reduce( (acc, val) => [...acc, getYear(val)], []);
return years[0] < years[1];
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
Try this one, edited for array of integers as Output
myValidator() {
range = "7-01-2018 VS 5-01-2019";
regEx = /\d{4}/g;
return (range.match(regEx).map(x => parseInt(x,10));
}
Output :
[ 2018, 2019 ]
Here's an example of the customer codes:
C000000123
C000000456
If I input C123 in the search box, "C000000123" will automatically display.
9 numbers are fixed.
Please help me, a short sample was shown to me but I don't get it.
function test(key, num, digit) {
let retStr;
xxxx (condition)
retun retStr;
}
here's an elaboration:
**
input:123
output:A00000123
input:1
output:A00000001
input:99999
output:A00099999
**
here's the detailed demand:
Since it takes time and effort to enter the management number “alphabet + numeric value 9 digits” on the search screen, when the alphabetic number and the number excluding the leading 0 are entered, it is automatically complemented so that it becomes 9 padded with zeros.
sorry i'm very very new to programming in javascript
Try this:
May be what you want...
Please test it and tell if its what you want.
function getOutput(input){
var str=input.substring(1,input.length);
var padd0=9-str.length;
var zr="000000000";
var zrsub=zr.substring(0,padd0);
var output=input[0]+zrsub+""+str;
return output;
}
//Example: Call it like (NB any letter can be used):
getOutput("C123"); //or
getOutput("D123");
You can use .endsWith in js which takes a string and a search string and returns true if the specified string ends with the search string.
This function takes an array of customer ids and a search string and returns the matching customer id
function searchCustomer(customers, searchString) {
return customers.find(customer => customer.endsWith(searchString));
}
searchCustomer(['C000000123', 'C000000456'], 123); // "C000000123"
searchCustomer(['C000000123', 'C000000456'], 456); // "C000000456"
searchCustomer(['C000000123', 'C000000456', 'A00000001'], 1); //"A00000001"
My submit click function is as below.
aAmt is a $ field like for eg. $45.00
a_amount is always 10000.
I am converting a_amount to $ in displayCurrencyFormat function.
I am then converting both to parseInt and doing >= comaprison and it fails. Even though aAmt is > $10000 and conition should display alert it doesnt.
$("#submitId").click(function () {
var aAmt = $("#aAmt").val();
var a_amount = "${dAmt}";
a_amount = displayCurrencyFormat(a_amount);
var pLen = $("#pOd").val();
if ((parseInt(aAmt) >= parseInt(a_amount)) && (pLen.length == 0)) {
$('#pDiv').text('Please provide a password');
$("#pOd").focus();
return false;
}
...//
});
function displayCurrencyFormat(a_amount)
{
//convert amount to currency format
var nbrAmt = Number(a_amount.replace(/[^0-9\.]+/g,""));
var fmtAmt = '$' + nbrAmt.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
return fmtAmt;
}
You should convert it into an integer-like data first, and then you can compare them.
The currency formatted input are considered as not a number format so comparing them are something like String to String comparison, not Number to Number like what you want to achieve.
Refrence link: How to convert a currency string to a double with jQuery or Javascript?
Do you know that parseInt('$10000') actually giving you "NaN"?
And as i can see here you are trying to compare integer and string...
Just try to alert aAmt and a_amount variables before you compare them and you will see what is actually going on...
I want to convert ObjectID (Mongodb) to String in JavaScript.
When I get a Object form MongoDB. it like as a object has: timestamp, second, inc, machine.
I can't convert to string.
Try this:
objectId.str
See the doc.
ObjectId() has the following attribute and methods:
[...]
str - Returns the hexadecimal string representation of the object.
in the shell
ObjectId("507f191e810c19729de860ea").str
in js using the native driver for node
objectId.toHexString()
Here is a working example of converting the ObjectId in to a string
> a=db.dfgfdgdfg.findOne()
{ "_id" : ObjectId("518cbb1389da79d3a25453f9"), "d" : 1 }
> a['_id']
ObjectId("518cbb1389da79d3a25453f9")
> a['_id'].toString // This line shows you what the prototype does
function () {
return "ObjectId(" + tojson(this.str) + ")";
}
> a['_id'].str // Access the property directly
518cbb1389da79d3a25453f9
> a['_id'].toString()
ObjectId("518cbb1389da79d3a25453f9") // Shows the object syntax in string form
> ""+a['_id']
518cbb1389da79d3a25453f9 // Gives the hex string
Did try various other functions like toHexString() with no success.
You can use $toString aggregation introduced in mongodb version 4.0 which converts the ObjectId to string
db.collection.aggregate([
{ "$project": {
"_id": { "$toString": "$your_objectId_field" }
}}
])
Use toString:
var stringId = objectId.toString()
Works with the latest Node MongoDB Native driver (v3.0+):
http://mongodb.github.io/node-mongodb-native/3.0/
Acturally, you can try this:
> a['_id']
ObjectId("518cbb1389da79d3a25453f9")
> a['_id'] + ''
"518cbb1389da79d3a25453f9"
ObjectId object + String will convert to String object.
If someone use in Meteorjs, can try:
In server: ObjectId(507f191e810c19729de860ea)._str.
In template: {{ collectionItem._id._str }}.
Assuming the OP wants to get the hexadecimal string value of the ObjectId, using Mongo 2.2 or above, the valueOf() method returns the representation of the object as a hexadecimal string. This is also achieved with the str property.
The link on anubiskong's post gives all the details, the danger here is to use a technique which has changed from older versions e.g. toString().
In Javascript, String() make it easy
const id = String(ObjectID)
this works, You have mongodb object: ObjectId(507f191e810c19729de860ea),
to get string value of _id, you just say
ObjectId(507f191e810c19729de860ea).valueOf();
In Js do simply: _id.toString()
For example:
const myMongoDbObjId = ObjectID('someId');
const strId = myMongoDbObjId.toString();
console.log(typeof strId); // string
You can use string formatting.
const stringId = `${objectId}`;
toString() method gives you hex String which is kind of ascii code but in base 16 number system.
Converts the id into a 24 character hex string for printing
For example in this system:
"a" -> 61
"b" -> 62
"c" -> 63
So if you pass "abc..." to get objectId you will get "616263...".
As a result if you want to get readable string(char string) from objectId you have to convert it(hexCode to char).
To do this I wrote an utility function hexStringToCharString()
function hexStringToCharString(hexString) {
const hexCodeArray = [];
for (let i = 0; i < hexString.length - 1; i += 2) {
hexCodeArray.push(hexString.slice(i, i + 2));
}
const decimalCodeArray = hexCodeArray.map((hex) => parseInt(hex, 16));
return String.fromCharCode(...decimalCodeArray);
}
and there is usage of the function
import { ObjectId } from "mongodb";
const myId = "user-0000001"; // must contains 12 character for "mongodb": 4.3.0
const myObjectId = new ObjectId(myId); // create ObjectId from string
console.log(myObjectId.toString()); // hex string >> 757365722d30303030303031
console.log(myObjectId.toHexString()); // hex string >> 757365722d30303030303031
const convertedFromToHexString = hexStringToCharString(
myObjectId.toHexString(),
);
const convertedFromToString = hexStringToCharString(myObjectId.toString());
console.log(`convertedFromToHexString:`, convertedFromToHexString);
//convertedFromToHexString: user-0000001
console.log(`convertedFromToString:`, convertedFromToString);
//convertedFromToHexString: user-0000001
And there is also TypeScript version of hexStringToCharString() function
function hexStringToCharString(hexString: string): string {
const hexCodeArray: string[] = [];
for (let i = 0; i < hexString.length - 1; i += 2) {
hexCodeArray.push(hexString.slice(i, i + 2));
}
const decimalCodeArray: number[] = hexCodeArray.map((hex) =>
parseInt(hex, 16),
);
return String.fromCharCode(...decimalCodeArray);
}
Just use this : _id.$oid
And you get the ObjectId string. This come with the object.
Found this really funny but it worked for me:
db.my_collection.find({}).forEach((elm)=>{
let value = new String(elm.USERid);//gets the string version of the ObjectId which in turn changes the datatype to a string.
let result = value.split("(")[1].split(")")[0].replace(/^"(.*)"$/, '$1');//this removes the objectid completely and the quote
delete elm["USERid"]
elm.USERid = result
db.my_collection.save(elm)
})
On aggregation use $addFields
$addFields: {
convertedZipCode: { $toString: "$zipcode" }
}
Documentation of v4 (right now it's latest version) MongoDB NodeJS Driver says: Method toHexString() of ObjectId returns the ObjectId id as a 24 character hex string representation.
In Mongoose, you can use toString() method on ObjectId to get a 24-character hexadecimal string.
Mongoose documentation
Below three methods can be used to get the string version of id.
(Here newUser is an object containing the data to be stored in the mongodb document)
newUser.save((err, result) => {
if (err) console.log(err)
else {
console.log(result._id.toString()) //Output - 23f89k46546546453bf91
console.log(String(result._id)) //Output - 23f89k46546546453bf91
console.log(result._id+"") //Output - 23f89k46546546453bf91
}
});
Use this simple trick, your-object.$id
I am getting an array of mongo Ids, here is what I did.
jquery:
...
success: function (res) {
console.log('without json res',res);
//without json res {"success":true,"message":" Record updated.","content":[{"$id":"58f47254b06b24004338ffba"},{"$id":"58f47254b06b24004338ffbb"}],"dbResponse":"ok"}
var obj = $.parseJSON(res);
if(obj.content !==null){
$.each(obj.content, function(i,v){
console.log('Id==>', v.$id);
});
}
...
You could use String
String(a['_id'])
If you're using Mongoose along with MongoDB, it has a built-in method for getting the string value of the ObjectID. I used it successfully to do an if statement that used === to compare strings.
From the documentation:
Mongoose assigns each of your schemas an id virtual getter by default which returns the document's _id field cast to a string, or in the case of ObjectIds, its hexString. If you don't want an id getter added to your schema, you may disable it by passing this option at schema construction time.
I am using an autocomplete Javascript function, and I need to extract the last 5 characters from 'value' and then compose URL for onSelect.
The function I am using is:
<script type="text/javascript">
var options, a;
jQuery(function(){
var onAutocompleteSelect = function(value, data) {
window.open('ITEM.PRO?id='+ value);
}
options = {
serviceUrl:'JQUERY-SEARCH.pro',
onSelect: onAutocompleteSelect,
};
a = $('#query').autocomplete(options);
});
</script>
When I click on search result it loads "ITEM.PRO?id=Article Brand Model Year Description 35612", but I need load "ITEM.PRO?id=35612"
Please could you help me? I am a totally newbie with JS.
Thank you all in advance!
Instead of window.open('ITEM.PRO?id='+ value); could you do this?
window.open('ITEM.PRO?id='+ value.split(' ').pop());
There are a few different ways to acheive this.
This simplest is to add
value = value.slice(-5);
right before
window.open('ITEM.PRO?id='+ value);
This sets value to its last 5 characters. Read here about the String.slice function.
If you want set the value to the last 'word', so to speak, delimited by spaces, you could do this instead:
value = value.split(" ").pop();
Another method would be to take the last continuous string of digits in the value. For that, you could use this:
value = value.match(/\d+/).pop();
Which method you use, of course, depends on what would work most reliably with the input you have.
Try this
var onAutocompleteSelect = function(value, data) {
window.open('ITEM.PRO?id='+ value.substring(value.length-5));
}
This is a terrible solution, but will work in the case you listed. I will edit if you post more details:
<script type="text/javascript">
var options, a;
jQuery(function(){
var onAutocompleteSelect = function(value, data) {
window.open('ITEM.PRO?id='+ value.match(/\d+/)[0]);
}
options = {
serviceUrl:'JQUERY-SEARCH.pro',
onSelect: onAutocompleteSelect,
};
a = $('#query').autocomplete(options);
});
</script>
value.match(/\d+/)[0] will match any digits in your string as any array, so we take the first item in that array.
When your IDs exceed 5 digits, your code will break (as has been stated in comments). You can also use the .split approach mentioned by #bordoz, the disadvantage being that spaces in any of the other words would break this solution. Or you could use:
var url = 'ITEM.PRO?id='+ value.replace(/[^\d\.]/g,'');
Which would fail only if any of the other word contain numbers. Which one best fits your situation?