I am trying to extract a substring (in this case the "Firstname") from a list of strings but I don't know the best approach in JavaScript
Here is the plain text list that I am working with:
Lead Code: LC123456789
Lead Type ID: 1
Firstname: Joe
Lastname: Bloggs
Addressline1: 123
Addressline2: NUMBER ROAD
I have tried string.split() and also tried using regex but that might be over complicating it
If you're given this whole input as a string (including linebreaks), then the best solution is most likely a regular expression. Try this:
const input = `Lead Code: LC123456789
Lead Type ID: 1
Firstname: Joe
Lastname: Bloggs
Addressline1: 123
Addressline2: NUMBER ROAD`;
const match = input.match(/Firstname: (.*)\n/)[1];
console.log(match);
This is the regex:
Firstname: (.*)\n
Firstname: will match the text preceding what you want, and (.*)\n will match any character up to the line break and put it in a match group. The .match() method returns an array of the match then all the match groups, so you need to get the second item (or first match group) with [1].
const s = `Lead Code: LC123456789
Lead Type ID: 1
Firstname: Joe
Lastname: Bloggs
Addressline1: 123
Addressline2: NUMBER ROAD`
console.log(s.match(/Firstname: (.*)/m)[1])
If you want to extract any "field" try to split every line first:
const arrFields = `Lead Code: LC123456789
Lead Type ID: 1
Firstname: Joe
Lastname: Bloggs
Addressline1: 123
Addressline2: NUMBER ROAD`.split("\n")
Then you can create an object with the fields:
const fields = {}
arrFields.forEach(el => {
const [key, val] = el.split(":")
fields[key] = val
})
After that you can access it:
console.log(fields["Firstname"]) // Joe
var a = `Lead Code: LC123456789
Lead Type ID: 1
Firstname: Joe
Lastname: Bloggs
Addressline1: 123
Addressline2: NUMBER ROAD`;
console.log(a.match(/^Firstname: (.*)/m)?.at(1));
A simple regex is a good approach here. And using the optional chaining (?.) operator will stop it from getting a TypeError when the regex does not match.
Related
I have a collection named users and I'm trying to add a user to the collection the code I'm using is
var user1 = {
Username: "joonyoftv",
Password: "joon123",
Email: "joony#bmail.com",
Birthday: {
new Date: ( "2000-08-02")
},
FavoriteMovies: [ 61942e53b8d3d951230f0980, 61943aabb8d3d951230f0983 ]
}
but i keep on getting an error that says SyntaxError: missing : after property id :
#(shell):6:7
What should i do?
It's just a simple JavaScript syntax error!
The new Date: ( "2000-08-02")" should not be in curly braces and ids in FavoriteMovies array should be enclosed in string literals.
Object with correct syntax:
var user1 = {
Username: "joonyoftv",
Password: "joon123",
Email: "joony#bmail.com",
Birthday: new Date("2000-08-02"), // corrected
FavoriteMovies: ["61942e53b8d3d951230f0980", "61943aabb8d3d951230f0983"],
//String ^ ^ ^ ^
};
I need to combine two different responses into one, both share a common key/value pair, distance. I need to combine these two json objects into one. sorted on distance.
I've tried doing it is way:
const test: [Group, Profile] = [].concat(profiles, groups)
export type Profile = {
userId: string
imageId: string
firstname: string
middleName: string
lastname: string
distance: number
}
export type Group= {
groupId: string
name: string
distance: number
}
Is this possible? im getting an error:
Argument of type 'Profile[]' is not assignable to parameter of type
'ConcatArray'.
Using concat is a little awkward because it assumes the arguments have the same type, but you can do it elegantly by spreading the arrays: [...profiles, ...groups].
Note that [Group, Profile] is not the right type for the result, as this is an array of length 2 containing a Group and a Profile. Instead, you can use an array of the union of Group and Profile, like this:
type ProfileOrGroup = Profile | Group
const test: ProfileOrGroup[] = [...profiles, ...groups]
TypeScript playground
interface Person {
name: string;
surname: string;
}
let person1: Person = {};
person1.name = "name"
person1.surname = "surname"
When I declare person1 I get this error:
Type '{}' is missing the following properties from type Person
This is a better way:
let person1: Person = {name: '', surname: ''};
But if you want exactly empty object than you can hack it like this:
let person1: Person = {} as Person;
Update after comment:
Look at this unpredictableFunction:
const unpredictableFunction = (): string|number|string[] => {
return Math.random() > 0.5 ? 'string' : Math.random() > 0.5 ? 9999 : ['1', '2', '3']
};
It may return number or it may return string or it may return array of strings
const person: Person = {name: '', surname: ''};
person.name = unpredictableFunction (); // this is a case you are talking about
In this case you will see
Type 'string | number | string[]' is not assignable to type 'string'.
Answers are:
Look at your code and ensure that you assign only strings to a Person properties,
Or update interface to be ready to a different values:
interface Person {
name: string | number | string[];
surname: string;
}
You have defined an interface with two required properties. So when you define an object with the type of the Person interface you must define these properties right away like this:
let person: Person = {
name: '',
surname: ''
}
However if you believe these properties are not required but are rather optional you can change your interface to this:
interface Person {
name?: string;
surname?: string;
}
Using the ? syntax you mark the property as optional. The following code should then work:
let person: Person = {};
in Typescript 2.0 we can do this better
let person1 ! : Person;
this "!" is Non-null assertion operator
according to documentation
A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
What is the correct syntax when extracting an object property from an array?
example
var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777",
email: "bob.jones#example.com"
};
var mary = {
firstName: "Mary",
lastName: "Johnson",
phoneNumber: "(650) 888 - 8888",
email: "mary.johnson#example.com"
}
var contact = [bob, mary];
console.log(contact[1.phoneNumber]); // <-- Need help here to print phoneNumber!
So when I want to print out the phoneNumber property from mary object using the contact array what is the correct syntax?
console.log(contact[1.phoneNumber]); will lead to an Unexpected token ILLEGAL cause there is not such number.
Try this instead:
console.log(contact[1].phoneNumber);
DEMO
I have the following Mongoose Schema
var People= new Schema({
firstName: String,
alias: [String]
});
I am looking for a way to return all documents where one of the alias strings match or exist as a substring within a given value.
For instance:
{ firstName: Jon
alias: ['foo', 'fuchs']}
{ firstName: Ann
alias: ['bar', 'fuchsbar']}
{ firstName: Paul
alias: ['foobar']}
If I pass in foob, I'd like to return Jon.
If I pass in foobar, I'd like to return Jon, Ann, and Paul.
If I pass in fuchs, I'd like to return Jon.
Is it possible to do such a substring query in Mongo?
I recommend that you index alias field and then generate your query the following way for string "fuchs":
db.people.find( { "alias" : { "$in" : [ "f","fu","fuc", "fuch", "fuchs" ] } } )
You'll need to generate appropriate list of $in values yourself, I'm afraid, there is no built in functionality for this in the query language.