Check file name suffix if .js - javascript

I need to check if file name suffix is type JavaScript (JS files end with *.js)
for that I use the following code which works
var ext = aa.getName().substr(aa.getName().lastIndexOf('.') + 1);
Now the problem is that if the file is named file2.json I'm still getting true (it's return json)
My question is if there a better way to do it i.e. given any file name like
file1.xml, file2.js, file3.json or file4.html, it will return true just for file2.

I believe this can work
function check(str){
if(str.match(/(\w*)\.js$/) == null){
console.log('false');
return false;
}
else {
console.log('true');
return true;
}
}
check('file1.xml');
check('file2.js');
check('file3.json');
check('file4.html');

let isJS = function(filename) {
return /\.js$/i.test(filename)
}
console.log(isJS("asd.json")) // false;
console.log(isJS("asdjs")) // false;
console.log(isJS("asd.js")) // true;
console.log(isJS("asd.JS")) // true;

You could check if string ends with .js with the following function:
function isJavascriptFile(str) {
var regex = /\.js$/;
var match = str.match(regex);
return match !== null;
}
According to your code you would use it like this:
var name = aa.getName();
isJavascriptFile(name);

I think for this case better not using regex,
var arr = [
'file1.xml',
'file2.js',
'file3.json',
'file4.html'
];
for(var i=0, len=arr.length; i<len; i++){
if(returnExtension(arr[i]) == 'js') {
alert('Your file is: ' + arr[i])
}
}
function returnExtension(filename){
var a = filename.split(".");
if( a.length === 1 || ( a[0] === "" && a.length === 2 ) ) {
return "";
}
return a.pop();
}
my working example is here https://jsfiddle.net/gat8mx7y/

You've to modify your code a little bit, you're almost right:
funciton isJavascriptFile(fileName){
var ext = fileName.substr(fileName.lastIndexOf('.') + 1);
if(ext === 'js'){ return true; }
return false;
}
if(isJavascriptFile(aa.getName()) ) {
console.log("file is javascript");
}

//function GetJSName(){
var filename="sample.js";
var name = filename.split('.')[0];
alert(name);
//};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

How to convert xml to JSON in suitescript 2.0

I have an XML response that i want to convert it to JSON, i'm currently usingg XPath
var responseNode = xml.XPath.select({
node : xmlDocument,
xpath : '//SOAP-ENV:Envelope'
});
and it is not very efficient because to extract data from one xml tag, i have to write a lot of extra code. I tried using external libs with suitescript but they didn't worked. Is there any better way to convert XML to JSON
I have a project that needs to convert xml to json rencently, so I wrote the following function.
require(['N/xml'], function (xmlMod) {
//This function refer to https://davidwalsh.name/convert-xml-json
function xmlToJson(xmlNode) {
// Create the return object
var obj = Object.create(null);
if (xmlNode.nodeType == xmlMod.NodeType.ELEMENT_NODE) { // element
// do attributes
if (xmlNode.hasAttributes()) {
obj['#attributes'] = Object.create(null);
for (var j in xmlNode.attributes) {
if(xmlNode.hasAttribute({name : j})){
obj['#attributes'][j] = xmlNode.getAttribute({
name : j
});
}
}
}
} else if (xmlNode.nodeType == xmlMod.NodeType.TEXT_NODE) { // text
obj = xmlNode.nodeValue;
}
// do children
if (xmlNode.hasChildNodes()) {
for (var i = 0, childLen = xmlNode.childNodes.length; i < childLen; i++) {
var childItem = xmlNode.childNodes[i];
var nodeName = childItem.nodeName;
if (nodeName in obj) {
if (!Array.isArray(obj[nodeName])) {
obj[nodeName] = [
obj[nodeName]
];
}
obj[nodeName].push(xmlToJson(childItem));
} else {
obj[nodeName] = xmlToJson(childItem);
}
}
}
return obj;
};
var str = '<?xml version="1.0"?><ALEXA VER="0.9" URL="davidwalsh.name/" HOME="0" AID="="><SD TITLE="A" FLAGS="" HOST="davidwalsh.name"><TITLE TEXT="David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else">Hello World</TITLE><LINKSIN NUM="1102">Netsuite</LINKSIN><SPEED TEXT="1421" PCT="51"/></SD><SD><POPULARITY URL="davidwalsh.name/" TEXT="7131"/><REACH RANK="5952"/><RANK DELTA="-1648"/></SD></ALEXA>';
var xmlObj = xmlMod.Parser.fromString({
text: str
});
var jsonObj = xmlToJson(xmlObj.documentElement);
log.debug('jsonObj', jsonObj);
});
The cenvert function referred to David Walsh's function located at: https://davidwalsh.name/convert-xml-json
I just revised it compatible with Netsuite.
Hope it works for you.
Here's a sample function from my NetSuite environment. I did not write this,but it is currently working.
//*********** PARSE XML INTO JSON ***********
function nsXMLToJSON(node){
var obj=nsXMLToJSONDirty(node);
var cleanObj=cleanObject(obj,true);
return cleanObj;
//*********** HELPER FUNCTIONS ***********
function nsXMLToJSONDirty(node){
var obj={};
if(!'nodeType' in node){
return obj;
}
if(node.nodeType==1 || node.nodeType=='ELEMENT_NODE'){
if(Object.keys(node.attributes).length > 0){
obj["#attributes"]={};
for(var j in node.attributes){
var attribute=node.attributes[j];
if(attribute){
obj["#attributes"][attribute.name]=attribute.value;
}
}
}
}else if(node.nodeType==3 || node.nodeType=='TEXT_NODE'){
obj=node.nodeValue;
}
if(node.hasChildNodes()){
var childNodes=node.childNodes;
for(var k in childNodes){
var item=childNodes[k];
var nodeName=item.nodeName;
if(typeof (obj[nodeName])=="undefined"){
obj[nodeName]=nsXMLToJSONDirty(item); //run the function again
}else{
if(typeof (obj[nodeName].push)=="undefined"){
var old=obj[nodeName];
obj[nodeName]=[];
obj[nodeName].push(old);
}
obj[nodeName].push(nsXMLToJSONDirty(item));
}
}
}
return obj;
}
function cleanObject(myobj,recurse){
var myobjcopy=JSON.parse(JSON.stringify(myobj));
for(var i in myobjcopy){
if(recurse && typeof myobjcopy[i]==='object'){
if(i=="#text"){
delete myobjcopy[i];
} else {
//Check if it only contains a text object
if(Object.keys(myobjcopy[i]).length==1){
if(typeof myobjcopy[i]['#text'] != "undefined"){
if(myobjcopy[i]['#text'] || myobjcopy[i]['#text']==0){
myobjcopy[i]=myobjcopy[i]['#text'];
}
}
}else{
//Handle empty objects
if(Object.keys(myobjcopy[i]).length==0){
myobjcopy[i]=undefined;
}
}
if(myobjcopy[i]){
myobjcopy[i]=cleanObject(myobjcopy[i],recurse);
}
}
}
}
return myobjcopy;
}
}
create a helper.js file so the function can be shared across different scripts.
define(["N/xml"], function (xml) {
function xmlToJson(text) {
function xmlNodeToJson(xmlNode, obj) {
var sibling = xmlNode;
while (sibling) {
if (sibling.nodeType == xml.NodeType.COMMENT_NODE) {
sibling = sibling.nextSibling;
continue;
}
if (sibling.nodeType == xml.NodeType.TEXT_NODE) {
if (!!sibling.nodeValue.replace(/[\n| ]/g, ''))
obj[sibling.nodeName] = sibling.nodeValue;
sibling = sibling.nextSibling;
continue;
}
var childObj = Object.create(null);
if (!!sibling.hasAttributes()) {
Object.keys(sibling.attributes).forEach(function (key) {
childObj[key] = sibling.getAttribute({ name: key });
});
}
var value = xmlNodeToJson(sibling.firstChild, childObj);
if ((sibling.nodeName in obj)) {
if (!Array.isArray(obj[sibling.nodeName])) {
obj[sibling.nodeName] = [obj[sibling.nodeName]];
}
obj[sibling.nodeName].push(value);
} else {
obj[sibling.nodeName] = value;
}
sibling = sibling.nextSibling;
}
return obj;
}
var xmlDocument = xml.Parser.fromString({ text: text });
return xmlNodeToJson(xmlDocument.firstChild, Object.create(null));
}
return {
xmlToJson: xmlToJson
}
});
import the helper file and use the xmlToJson function in your script.
define(['N/file', '/SuiteScripts/PATH_TO_HELPER_FILE/helper'], function(file, helper) {
...
var string = file.load({ id: '/SuiteScripts/PATH_TO_FILE/filename.xml' }).getContents()
var json_object = helper.xmlToJson(string);
...
})

Javascript - converts dash/underscore delimited words into camel casing

Here is a code that works for "underscore" perfectly :
function toCamelCase(input){
return input.toLowerCase().replace(/-(.)/g, function(match,group1)
{
return group1.toUpperCase();
});
}
But when i tried to add for either "underscore" or "hyphen" in regex,the below code is not working telling me that
" Uncaught TypeError: Cannot read property 'toUpperCase' of undefined "
function toCamelCase(input){
return input.toLowerCase().replace(/-(.)|_(.)/g, function(match,group1)
{
return group1.toUpperCase();
});
}
Can anyone please tell me why it is not working and rectify the code please ?
Simply change your regex to /[-_](.)/g
function toCamelCase(input) {
return input.toLowerCase().replace(/[-_](.)/g, function(match, group1) {
return group1.toUpperCase();
});
}
const s = 'foo-bar_baz';
console.log(toCamelCase(s));
One alternate to what #bambam posted is using split and join
function toCamelCase(input) {
return input.split(/[-_]/).map(e => e[0].toUpperCase() + e.substr(1,).toLowerCase()).join('');
}
const s = 'foo-bar_baz';
console.log(toCamelCase(s));
Or using a simple for loop.
function toCamelCase(input) {
let result = ''
input = input.toLowerCase()
for(let i=0; i< input.length; i++){
if(input[i] === '_' || input[i] === '-'){
i++;
result += input[i].toUpperCase()
} else {
result+= input[i]
}
}
return result
}
const s = 'foo-bar_baz';
console.log(toCamelCase(s));

JavaScript If / else statement not return false statement

Function returns true, however if / else statement is logging false result. Any idea where I'm going wrong?
function loginDetails(arrayCheck, value) {
for(i = 0; i < arrayCheck.length; i++){
if(arrayCheck[i] === value){
return true;
}
}
return false;
}
var username = [1,2,3,4,5,6,7,8,9,10];
document.write('Login Details: ', loginDetails(username, 9), '</p>');
if(loginDetails === true) {
document.write('Redirect ....Welcome !!</p>');
} else {
document.write('There seems to be an error please try again !!');
}
loginDetails is a function. You then test to see if it is boolean true. Funnily enough, it never will be!
I presume you actually want to run the function. You will need to cache the result in order not to run it twice:
function loginDetails(arrayCheck, value) {
for(i = 0; i < arrayCheck.length; i++){
if(arrayCheck[i] === value){
return true;
}
}
return false;
}
var username = [1,2,3,4,5,6,7,8,9,10];
var loggedIn = loginDetails(username, 9);
document.write('Login Details: ', loggedIn, '</p>');
if(loggedIn === true) {
document.write('Redirect ....Welcome !!</p>');
} else {
document.write('There seems to be an error please try again !!');
}
What do you mean by if(loginDetails === true) ? This doesn't pass any parameters to loginDetails function.
Instead try if(loginDetails(username, 9) === true). Hope this works. Else store loginDetails(username, 9) in a variable and check whether that variable is true?
loginDetails is a function I suppose you want to check its result to be equal with true.
function loginDetails(arrayCheck, value) {
for(i = 0; i < arrayCheck.length; i++){
if(arrayCheck[i] === value){
return true;
}
}
return false;
}
var username = [1,2,3,4,5,6,7,8,9,10];
var loginDetailsResult = loginDetails(username, 9);
document.write('Login Details: ',loginDetailsResult, '</p>');
if(loginDetailsResult === true) {
document.write('Redirect ....Welcome !!</p>');
} else {
document.write('There seems to be an error please try again !!');
}
You are checking if the reference to the function is equal to true, which will always evaluate to false. A function and a boolean are different types and therefore comparing for strict equality will always return false. I have corrected the code, so that the function is called, and the result of the function is compared, instead of the reference to the function.
function loginDetails(arrayCheck, value) {
for(i = 0; i < arrayCheck.length; i++){
if(arrayCheck[i] === value){
return true;
}
}
return false;
}
var username = [1,2,3,4,5,6,7,8,9,10];
document.write('Login Details: ', loginDetails(username, 9), '</p>');
if(loginDetails(username, 9) === true) {
document.write('Redirect ....Welcome !!</p>');
} else {
document.write('There seems to be an error please try again !!');
}

how to manage 100's of else if statement in javascript? better way?

I am learning javascript. I am trying to answer my quiz - classify urls. How can I improve my answer for classifying 100 urls.. my answer is not so efficient.. any help? thanks.
var pageURL = document.location.href;
var isHealth = pageURL.indexOf("http://www.domain.com/health/");
var isCar = pageURL.indexOf("http://www.domain.com/car/");
var isFuel = pageURL.indexOf("http://www.domain.com/fuel/");
var isRoadside = pageURL.indexOf("http://www.domain.com/roadside/");
if (isHealth > -1) {
return 'health';
} else if (isCar > -1) {
return 'car';
} else if (isRoadside > -1) {
return 'roadside';
} else if (isFuel > -1) {
return 'fuel';
} else return 'other';
You can use map object and for loop to check what url matches current page:
var urls = {
health: "http://www.domain.com/health/",
car: "http://www.domain.com/car/",
roadside: "http://www.domain.com/fuel/",
fuel: "http://www.domain.com/roadside/"
};
var pageURL = document.location.href;
for (var key in urls) {
if (pageUrl.indexOf(urls[key]) > -1) {
return key;
}
}
return "other";
You can map them together like this, but I'm not sure if it's worth it:
var map = {
'health': isHealth,
'car': isCar,
'roadside': isRoadside,
'fuel': isFuel
}
for (var i in map) {
if (map[i] > -1) {
return i;
}
}
return 'other';
That's the general approach.
Better idea
But, your specific problem is easily solvable using regex:
var match = pageURL.match(/http:\/\/www.domain.com\/(.+)\//);
return (match && match[1]) || 'other';
See this live example:
function test(pageURL) {
var match = pageURL.match(/http:\/\/www.domain.com\/(.+)\//);
return (match && match[1]) || 'other';
}
alert(test('http://www.domain.com/health/')); // health
alert(test('http://www.domain.com/whatever/')); // whatever
alert(test('http://www.domain.com/')); // other
why not ?
var pages = ['health', 'car', 'fuel']
var page = pageURL.split('//')[1].split('/')[1] || -1;
var index = pages.indexOf(page)
if (index !=-1)
return pages[index]
else
return 'other'
"JavaScript Trie Performance Analysis" discusses how to use Tries in JavaScript to do compact, efficient prefix lookup.
It looks like most of your checks can be boiled down to "does the string s start with a URL prefix." This kind of longest prefix check is exactly what Tries were designed to do.
If the bodies of your if ... else if ... else are not formulaic, you could store functions encapsulating those bodies as the value of the trie.

Getting nested obj value

Given the following obj:
var inputMapping = {
nonNestedItem: "someItem here",
sections: {
general: "Some general section information"
}
};
I'm writing a function to get that data by passing in a string "nonNestedItem" or in the nested case "sections.general". I'm having to use an eval and I was wondering if there was maybe a better way to do this.
Here is what I have so far and it works okay. But improve!
function getNode(name) {
var n = name.split(".");
if (n.length === 1) {
n = name[0];
} else {
var isValid = true,
evalStr = 'inputMapping';
for (var i=0;i<n.length;i++) {
evalStr += '["'+ n[i] +'"]';
if (eval(evalStr) === undefined) {
isValid = false;
break;
}
}
if (isValid) {
// Do something like return the value
}
}
}
Linky to Jsbin
You can use Array.prototype.reduce function like this
var accessString = "sections.general";
console.log(accessString.split(".").reduce(function(previous, current) {
return previous[current];
}, inputMapping));
Output
Some general section information
If your environment doesn't support reduce, you can use this recursive version
function getNestedItem(currentObject, listOfKeys) {
if (listOfKeys.length === 0 || !currentObject) {
return currentObject;
}
return getNestedItem(currentObject[listOfKeys[0]], listOfKeys.slice(1));
}
console.log(getNestedItem(inputMapping, "sections.general".split(".")));
You don't need to use eval() here. You can just use [] to get values from an object. Use a temp object to hold the current value, then update it each time you need the next key.
function getNode(mapping, name) {
var n = name.split(".");
if (n.length === 1) {
return mapping[name];
} else {
var tmp = mapping;
for (var i = 0; i < n.length; i++) {
tmp = tmp[n[i]];
}
return tmp;
}
}

Categories