I want to do String validation [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
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));

Related

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);

Using Dynamic data in a Regular Expression [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
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);

search() javascript doesn't work if first character there isn't in the string [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 6 years ago.
Improve this question
Hello I know that search() in javascript doesn't work (returns -1) if first charachter does not exist in the string...
$('#search-vulc').on('keyup', function() {
var textinsert = ($(this).val()).toLowerCase();
var nome_search = "home";
if (nome_search.search(textinsert) != -1) {
alert('ok');
}
else {
alert('not');
}
});
And so in this example if we write "x home", returns -1.
But is there a way to "solve" this problem ?
in short, if i write "x home" anyway there is the word home...
I would like a method that in this case doesn't return -1
You're searching for "x home" in "home".
Thus it is returning -1.
if (nome_search.search(textinsert) != -1)
Should be
if (textinsert.search(nome_search) != -1)
Is this nome_search.search(textinsert) simply backwards? textinsert.search(nome_search)
Refactored code:
function getStringPostion(re, str) {
var midstring;
var position = str.search(re);
midstring=(position != -1) ? ' contains ':' does not contain ';
console.log(str + midstring + re);
console.log(position );
return position;
}
var foundAtPosition = getStringPostion("home","x home");
Iterating trough all the inserted strings might do:
var f = function(re) {
var textinsert = ($(this).val()).toLowerCase().split(" ");
var nome_search = "home";
var result = 0;
for (var i = 0; i<textinsert.length; i++){
console.log(textinsert[i]);
if (nome_search.search(textinsert[i]) != -1) result++;
}
return result > 0 ? alert('ok') : alert('not') ;
};
as long as they are separated by spaces like in your example.

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());

How to execute if condition based on a value from query string in javascript/jquery? [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 8 years ago.
Improve this question
I've a variable called url as follows :
url = "http://56.177.59.250/static/ajax.php?core[ajax]=true&core[call]=prj_name.contactform&width=400&core[security_token]=c7854c13380a26ff009a5cd9e6699840"
Now I want to use if condition only if core[call] is equal to the value it currently has i.e. prj_name.contactform otherwise not.
How should I do this since the parameter from query-string is in array format?
Just use String.indexOf and check if it is present (that is not -1, which means it doesn't exist)
if(url.indexOf("core[call]=prj_name.contactform") > -1){
// valid. Brew some code here
}
You can use location.search :
<script>
function get(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
if(get("core[call]") == "prj_name.contactform"){
alert('ok');
}else{
alert('no');
}
</script>

Categories

Resources