Using Dynamic data in a Regular Expression [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a list that looks something like this :
listA = ["Physics","English","Chemistry","Biology","History","Human Values","None"]
The web page shows a textArea, where the user can add data like :-
Hello, My fav subject is <<English>>
or
I like <<Biology>> , its the best
I want to show a validation error if the user enters anything else from what in the listA between the <<>>, the rest of message can be anything.
I tried using regular expression but I cant figure it out and I couldn't figure out directives. Please ask if more clarification is required
this is what I have tried so far :
checkText(event) {
// const regex = /(?:^|\s)<<(.*?)>>(?:\s|$)/g;
var str = this.editClauseObj.textObj.text;
console.log("str",str);
let name_val = 'Name';
const regex = /^([a-zA-Z]*\s)*[<<name_val>>]*\s*[a-zA-Z\s]*$/g
if (!regex.test(str)) {
this.showError = true;
this.errorMessage = "Please enter a valid value inside <<>>"
console.log("test", this.showError);
} else {
// do something else
this.showError = false;
}
}

const listA = ["Physics","English","Chemistry","Biology","History","Human Values","None"];
const text = "Hello, My fav subject is <<English>> \n I like <<Biology>> , its the best \n I like <<Hello>> , its the best ";
// Look for << char and then ([^>>]+) except this >> char for 1 and more time and find the next >> char.
const r = /<<([^>>]+)>>/g
let found=[];
while( current_found = r.exec( text ) ) {
found.push( current_found[1] );
}
// all found items in the text
console.log(found);
// filter which is not matching
var final = found.filter(function(item) {
return !listA.includes(item);
});
console.log(final);

Related

Need to have one string from Looped Chars JS [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
need to get the output as 1 string instead of looped string
the output I got each letter on its own
need to have the second output which is one word
Thanks in advance:D
let start = 0;
let swappedName = "elZerO";
for (let i = start; i<swappedName.length; i++){
if (swappedName[i] == swappedName[i].toUpperCase()) {
console.log(swappedName[i].toLowerCase());
}else {
console.log(swappedName[i].toUpperCase());
}
}
//Output
E
L
z
E
R
o
// Need to be
"ELzERo"
Use string = string0+string1 , or keep adding values to an array, then join the array with array.join()
MasteringJs has a great guide on ways to merge characters and strings.
let start = 0;
let swappedName = "elZerO";
var outputString="";
var outputStringArray=[];
var newChar="";
for (let i = start; i<swappedName.length; i++){
if (swappedName[i] == swappedName[i].toUpperCase()) {
newChar = swappedName[i].toLowerCase();
}else {
newChar=swappedName[i].toUpperCase();
}
outputStringArray.push(newChar);
outputString+=newChar;
}
console.log("[Output using string1 + string 2] is "+outputString); // Another example of concating string
console.log("[Output using array.join] is "+outputStringArray.join("")); // Another example of concating string
// Need to be
"ELzERo"

How to split a name string with multiple spaces? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
i want to sort firstname and lastname, my problem is when the user has multiple first name, e.g.:
'Michael Jordan Atticus Smith'
basically, the Smith is the last name there, how do i split firstname and lastname with it? the result i want from is:
'Michael Jordan Atticus' 'Smith'
let str = 'Michael Jordan Atticus Smith';
console.log( ex1(str) );
console.log( ex2(str) );
console.log( ex3(str) );
function ex1(str) {
let names = str.match(/(.*?)\s(\S+)$/); // (1)
return [ names[1], names[2] ];
}
function ex2(str) {
let names = str.split(" ");
return [names.pop(), names.join(" ")].reverse(); // (2)
}
function ex3(str) {
let last = ""
str = str.replace(/\s(\S+)$/, function(full_match, parenthesis_1) {
last = parenthesis_1;
return "";
});
return [str, last];
}
(1) match() returns an array of matched strings. Also, see the RegEx cheet sheet
(2) Array pop() method removes, and returns the last element. Code executes from the left to right, so, the second names.join(" ") collects together 3 names left.

How to count character followed by Special Character in string using Javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
My string is: Hello 1⃣2⃣3⃣ world.
The expected result is 3 (1⃣ 2⃣ and 3⃣)
Matching condition has total 12 value below:
(0⃣ 1⃣ 2⃣ 3⃣ 4⃣ 5⃣ 6⃣ 7⃣ 8⃣ 9⃣ *⃣ #⃣ )
How to use javascript to count total of result? Thank you.
// Get code of emoji
function getEmojiUnicode(emoji) {
var comp;
if (emoji.length === 1) {
comp = emoji.charCodeAt(0);
}
comp = (
(emoji.charCodeAt(0) - 0xD800) * 0x400
+ (emoji.charCodeAt(1) - 0xDC00) + 0x10000
);
if (comp < 0) {
comp = emoji.charCodeAt(0);
}
return comp.toString("16");
};
// count how many times emoji appears
function countSpecialCharacter(string) {
// what should I write here?
return result;
}
var inputString = 'Hello 1⃣2⃣3⃣ world';
var output = countSpecialCharacter(inputString); // this should be 3
Definition of Combining Enclosing Keycap is here
https://emojipedia.org/combining-enclosing-keycap/
1) Split the string by ' ' and get the words
2) Check each word if it had enclosing keyCap
3) If so, return length/2 (because each char has one enclose)
const count = line => {
const valid_chars = Array.from("0123456789*#");
const sp_chars = line.split(" ").find(x => x.includes("⃣"));
if (sp_chars && sp_chars.length % 2 === 0) {
return Array.from(sp_chars).filter(x => valid_chars.includes(x)).length;
}
return 0;
};
console.log(count("Hello 1⃣2⃣3⃣-⃣ world"));
I think what you need to do is iterate through each character you have in your string, looking at the unicode character. Once you have this you can compare this to a list of unicode characters you know are 'Keycaps' - giving you the count.
I.e (this is just checking the first character in a string as an example):
function isCharacterAKeycap(str) {
var keycapUnicodeValues = [8000, 8001, 8002];
return keycapUnicodeValues.includes(str.charCodeAt[0]);
}
str = "1⃣";
isCharacterAKeycap(str);

I want to do String validation [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
We need to consider the below string as use cases , First I want to split
by "," then by "#"
After Splitting by # if all the domain are same(either all gmail or all yahoo) its valid
else invalid.
Help me with split part.
String input1 = example#gmail.com , example1#gmail.com;
String input2 = example#yahoo.com , example1#gmail.com;
String input 1 == valid.
String input 2 == Invalid.
Use a function
isValid = (emails)=>{
let list = emails.split(','), isValid = true
list.forEach((email)=>{
if(!email.includes('#gmail.com')){
isValid = false
}
})
return isValid
}
isValid(' example#gmail.com , example1#hotmail.com;')
Split by ,
Then check each email with includes
You could add a secound parameter to check the email type and make it more universal
isValid = (emails, validEmail)=>{
let list = emails.split(','), isValid = true
list.forEach((email)=>{
if(!email.includes(validEmail)){
isValid = false
}
})
return isValid
}
isValid(' example#gmail.com , example1#hotmail.com', '#gmail.com')
Here is a simple example, you can access array from the split with [0] and [1].
var input = 'example#gmail.com , example1#ymail.com, example1#yahoo.com';
input.split(',').forEach(email => {
const domain = email.split('#')[1].trim();
if (domain === 'gmail.com' || domain === 'yahoo.com') {
console.log("Email address " + email + " is valid.");
} else {
console.log("Email address " + email + " is not valid.");
}
})
You could extract the domains, and then add them to a Set and see if they were unique by checking the size of the Set.
An added extra, is that this will work regardless of the number of emails in the string.
const input1 = 'example#gmail.com , example1#gmail.com';
const input2 = 'example#yahoo.com , example1#gmail.com';
function validInput(input) {
const domains = input.split(',').map(email => email.trim().split('#')[1])
return new Set(domains).size === 1;
}
console.log('is input1 valid ?',validInput(input1));
console.log('is input2 valid ?',validInput(input2));

JavaScript prototypes - technical interview [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I had a JavaScript interview last wednesday, and I had trouble with one of the questions. Maybe you guys can give me hand with it?
The question was: how would you go about this printing var a and s to the console, in camel case, with the help of a prototype function...
var s = “hello javier”;
var a = “something else”;
String.prototype.toCamelCase = function() {
/* code */
return capitalize(this);
};
...so the result is the same as doing this?
console.log(s.toCamelCase());
console.log(a.toCamelCase());
>HelloJavier
>SomethingElse
Thanks!
var s = 'hello javier';
var a = 'something else';
String.prototype.toCamelCase = function() {
return capitalize(this);
};
function capitalize(string) {
return string.split(' ').map(function(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}).join('');
}
console.log(a.toCamelCase());
console.log(s.toCamelCase());
Reference
How do I make the first letter of a string uppercase in JavaScript?
I would go with something like this:
var s = "hello javier";
var a = "something else";
String.prototype.toCamelCase = function() {
function capitalize(str){
var strSplit = str.split(' ');
// starting the loop at 1 because we don't want
// to capitalize the first letter
for (var i = 1; i < strSplit.length; i+=1){
var item = strSplit[i];
// we take the substring beginning at character 0 (the first one)
// and having a length of one (so JUST the first one)
// and we set that to uppercase.
// Then we concatenate (add on) the substring beginning at
// character 1 (the second character). We don't give it a length
// so we get the rest.
var capitalized = item.substr(0,1).toUpperCase() + item.substr(1);
// then we set the value back into the array.
strSplit[i] = capitalized;
}
return strSplit.join('');
}
return capitalize(this);
};
// added for testing output
console.log(s.toCamelCase());
console.log(a.toCamelCase());

Categories

Resources