Need help extracting string from a text file via regex [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I'm trying to extract a certain js object from a text/js file via regex.
The whole file contains a lot of code, but I'm only interested in getting a variable called cfg.
The file could look like this:
function A(){
}
var cfg = {
setting:1,
setting2: 5,
setting3:[],
setting4:{
setting5:"test"
}
};
function B(){
}
Could anyone help me to figure out the regex for this ? I'm terrible at regex and I've tried plenty of available solutions but some of them don't seem to be valid in C#.
Right now my solution is using:
string[] split = input.Split(new string[] { "var cfg = " }, StringSplitOptions.None);
if(split.Length > 2)
{
string[] split2 = split[1].Split(new string[] { ";" }, StringSplitOptions.None);
return JObject.Parse(split2[0]);
}
Which obviously doesn't cover different writings of the cfg object. Like var cfg={};
Thanks in advance!

I would recoment you use a JS parser such as Jint if your code is more complex or will change. But for your example this should work:
var r = new Regex(#"var cfg = (?<Content>\{[^;]*});");
var content = r.Match(text).Groups["Content"];
Note: If the cfg literal contains ; the regex will not work as expected.

Related

Library to read numbers from a string in JS [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I'm asking if there is a method or library that reads easily numbers this type of input strings (like competitive programming):
2 3
0 1 20
1 2 2
0 2 17
I'm finding something like Scanner class of Java because it has methods to detect whether there is next number, it jumps to the next line,...
Thanks in advance!
Try with parseInt for reading numbers. Also you can get the array of numbers with strings like the ones you have provided with somehting like this:
var numbers = str.split(" ").map(function(item) { return parseInt(item); });
The best thing you can do is use functional programming to implement a set of methods you can use together in the way you see fit.
const byLine = (input) => input.split('\n');
const toInt = (el) => Number(el);
const getDigits = (el) => el.split(' ').map(toInt);
const flatten = (arr) => arr.reduce((p, c) => p.concat(c));
function scanner(input) {
return flatten(byLine(input).map(getDigits));
}
DEMO
If you have access to the lines, you could use the following:
var i, lines = [ /* your lines goes here */], row;
// get lines
for (i = 0; i < lines.length; i++) {
row = lines[i].split(' ').map(Number);
// do something with row
}

Give a second name to a variable in javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I have a code source that contains a long variable name (postCustomThumbnailsScrollerHeight).
I don't want to rename this variable for the whole code source so that I easily continue the project, but to have a shorthand of its name. I tried following solution (which works) at the first declaration of the variable, but I am not sure if it is the correct way to do so. I have a different color of d in IDE:
var postCustomThumbnailsScrollerHeight= d= $('.post-scroller').outerHeight();
I am seeking by this question your usual expert advice.
No, this isn't really correct: you're not declaring the d variable, only assigning to it, and thus
making it global (which may or not be desired)
making your code incompatible with strict mode
Here's a solution:
var d = $('.post-scroller').outerHeight(),
postCustomThumbnailsScrollerHeight = d;
Note that this should only be done for readability/typing issues, not for downloaded script size: minifiers should be used for that latter goal.
Be also careful that you're not making an alias, but really two variables. If you assign to one, you won't change the other one. It's hard to give a definite advice without more information but the usual solution is to have namespaced object:
Assuming you have a struct
myApp.thumbnailScrollers.postCustom = {height:...
then you would just assign that latter object to a local variable in a module or function:
var s = myApp.thumbnailScrollers.postCustom
In this case, changing s.height would also change myApp.thumbnailScrollers.postCustom.height.
Probably you have different color because in this case b it's global variable.
As for my opinion will be better to write all definitions on different lines:
var postCustomThumbnailsScrollerHeight = $('.post-scroller').outerHeight();
var d = postCustomThumbnailsScrollerHeight;
Although JavaScript doesn't natively support references, you can stimulate them using code such as this:
function d(){
return postCustomThumbnailsScrollerHeight;
}
Then just use d() everywhere. It's not very elegant, but as far as I know it's the only way to get a reference in JavaScript.
Do you have a problem declaring that var in the next line?
You could just do:
var postCustomThumbnailsScrollerHeight = $('.post-scroller').outerHeight();
var d = postCustomThumbnailsScrollerHeight;

Typed immutable objects in javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I am trying organize data types in React Flux-like application. All my data objects are immutable, for collections I am using immutable.js, which is perfect library for that. But for typed objects i use my own classes. I don't think it is the best solution, but i need to somehow handle default values, internal consistency, validations of data, add methods to that objects etc.
Is there some library available for that purpose?
Do you use immutable.js collections also for that kind of objects? So you handle consistency of data, validations and other functionality somewhere else?
Or do you use plain classes for that?
Do you think that is good idea to have typed objects in React/Flux based application?
Here is example of what kind of objects i mean and simple example how I use it.
class Event extends MyImmutableLib {
constructor(plain) {
this.start = plain.start;
this.end = plain.end;
this.name = plain.name || "unnamed event"; // some default value
this.attendants = plain.attendants || [];
this.valid = plain.start < plain.end; // simple check of validity, I can also throw exception if it is needed
Object.freeze(this); // I use freeze to be sure I don't accidentally change the object
}
getDuration() {
return this.end - plain.start; // methods are sometimes useful
}
addAttendant(newPerson) {
return this.set("attendants", this.attendants.concat([newPerson])) //immutable edit, so I return new object
}
}
var someEvent = new Event({start: new Date("2015-02-29"), end: new Date("2012-02-30")}) //
var jsMeetup = someEvent.set("name", "9th Js Meetup, Brno")
var jsMeetup = jsMeetup.addAttendant("Joe");
console.log(jsMeetup.name, jsMeetup.getDuration())
The best would be some library with:
Typed objects - so I would have my data better organized.
Default values
Validations
Methods
Immutability specific functions

How to get the array of strings that is in between curly braces inside source string in JavaScript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Suppose the JavaScript variable is:
var sourceString="stack {overflow} is the best {place} to clear {technical} doubts";
Output javascript string array should contain: overflow,place,technical
or {overflow},{place},{technical}
I am fine with both the results.
You could use regex to accomplish this:
sourceString.match(/{.*?}/g)
var getMatchingGroups = function(s) {
var r=/\{(.*?)\}/g, a=[], m;
while (m = r.exec(s)) {
a.push(m[1]);
}
return a;
};
getMatchingGroups(sourceString) // ["overflow", "place", "technical"]

How do I cut out a piece of a big string with javascript? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In javascript, I have a large string like
str="a lot of lines\n"
str+="foo\n"
str+="the stuff I want\n"
str+="bar and a lot more stuff\n"
How do I put just the part:
the stuff I want
between "foo" and "bar" into a new string variable?
Depending on where exactly 'the stuff you want' is in the string you can do a similar approach to this one:
var str="a lot of lines\n";
str+="foo\n";
str+="the stuff I want\n";
str+="bar and a lot more stuff\n";
var stuff = str.split('\n')[2]; // the stuff i want
EDIT:
If you want the stuff between foo and bar, then you can do something like:
var stuff = str.match(/foo((.|\n)*)bar/)[1]; // contains newlines!
var str = "a lot of lines foo the stuff I want bar and a lot more stuff"
str.substring(str.indexOf("foo")+3,str.indexOf("bar") )
var str="a lot of lines\n";
str+="foo\n";
str+="the stuff I want\n";
str+="bar and a lot more stuff\n";
// ------------------------------
var myRegex = /foo(.*)bar/;
if (myRegex.test(str)) {
alert(myRegex[0]);
}
With a regex, it should do the trick.

Categories

Resources