remove email address format from username - javascript

var login_id = 'sa-testaccount0125#abc.com';
console.log(login_id.substring(0, login_id.lastIndexOf("#")));
Above script works perfectly if I pass input with '#abc.com'. Does not work if string do not have '#domain.com'
We have some user name with username#domain.com and few are just username. I want extract #domain.com from user name. Expected output is if input is username#domain.com return output = username and if input is username, output should be username.
Please help if there is any way.

Use .split() method to split your string in parts
It will still work if you do not have #domain.com
Case-1:
const login_id = 'sa-testaccount0125#abc.com';
console.log(login_id.split("#")[0])
Output
"sa-testaccount0125"
Case-2:
const login_id = 'sa-testaccount0125';
console.log(login_id.split("#")[0])
Output
"sa-testaccount0125"

If you split on # then you get an array of items. The first item of the array will be the username, whether there was a # in it or not.
const test = str => str.split('#')[0]
console.log(test('sa-testaccount0125#abc.com'));
console.log(test('sa-testaccount0125'));

You're already using a indexOf. Usee that to check # if exists as well:
function check(login_id) {
if (login_id.indexOf('#') >= 0) {
return login_id.substring(0, login_id.lastIndexOf("#"));
}
return login_id;
}
console.log(check('sa-testaccount0125#asdasdasd.com'));
console.log(check('sa-asd'));
console.log(check('sa-asasd#domain.com'));

check first if it contains the '#' charactar first
login_id.includes('#') ? console.log(login_id.substring(0,
login_id.lastIndexOf("#"))) : console.log(login_id) ;
Running example
function username(login_id) {
return login_id.includes('#') ? login_id.substring(0,login_id.lastIndexOf("#")) : login_id ;
}
console.log(username("sa-testaccount0125#abc.com")) ;
console.log(username("sa-testaccount0125")) ;

Related

Looking for the easiest way to extract an unknown substring from within a string. (terms separated by slashes)

The initial string:
initString = '/digital/collection/music/bunch/of/other/stuff'
What I want: music
Specifically, I want any term (will never include slashes) that would come between collection/ and /bunch
How I'm going about it:
if(initString.includes('/digital/collection/')){
let slicedString = initString.slice(19); //results in 'music/bunch/of/other/stuff'
let indexOfSlash = slicedString.indexOf('/'); //results, in this case, to 5
let desiredString = slicedString.slice(0, indexOfSlash); //results in 'music'
}
Question:
How the heck do I accomplish this in javascript in a more elegant way?
I looked for something like an endIndexOf() that would replace my hardcoded .slice(19)
lastIndexOf() isn't what I'm looking for, because I want the index at the end of the first instance of my substring /digital/collection/
I'm looking to keep the number of lines down, and I couldn't find anything like a .getStringBetween('beginCutoff, endCutoff')
Thank you in advance!
your title says "index" but your example shows you wanting to return a string. If, in fact, you are wanting to return the string, try this:
if(initString.includes('/digital/collection/')) {
var components = initString.split('/');
return components[3];
}
If the path is always the same, and the field you want is the after the third /, then you can use split.
var initString = '/digital/collection/music/bunch/of/other/stuff';
var collection = initString.split("/")[2]; // third index
In the real world, you will want to check if the index exists first before using it.
var collections = initString.split("/");
var collection = "";
if (collections.length > 2) {
collection = collections[2];
}
You can use const desiredString = initString.slice(19, 24); if its always music you are looking for.
If you need to find the next path param that comes after '/digital/collection/' regardless where '/digital/collection/' lies in the path
first use split to get an path array
then use find to return the element whose 2 prior elements are digital and collection respectively
const initString = '/digital/collection/music/bunch/of/other/stuff'
const pathArray = initString.split('/')
const path = pathArray.length >= 3
? pathArray.find((elm, index)=> pathArray[index-2] === 'digital' && pathArray[index-1] === 'collection')
: 'path is too short'
console.log(path)
Think about this logically: the "end index" is just the "start index" plus the length of the substring, right? So... do that :)
const sub = '/digital/collection/';
const startIndex = initString.indexOf(sub);
if (startIndex >= 0) {
let desiredString = initString.substring(startIndex + sub.length);
}
That'll give you from the end of the substring to the end of the full string; you can always split at / and take index 0 to get just the first directory name form what remains.
You can also use regular expression for the purpose.
const initString = '/digital/collection/music/bunch/of/other/stuff';
const result = initString.match(/\/digital\/collection\/([a-zA-Z]+)\//)[1];
console.log(result);
The console output is:
music
If you know the initial string, and you have the part before the string you seek, then the following snippet returns you the string you seek. You need not calculate indices, or anything like that.
// getting the last index of searchString
// we should get: music
const initString = '/digital/collection/music/bunch/of/other/stuff'
const firstPart = '/digital/collection/'
const lastIndexOf = (s1, s2) => {
return s1.replace(s2, '').split('/')[0]
}
console.log(lastIndexOf(initString, firstPart))

Recognize name out of user input

I want to make a basic AI chat in Javascript.
1) If a user says 'Hi, my name is Thore' I want to check what the closest match is with some predefined values.
My array looks like this:
const nameSentences = [`my name is`, `i'm`, `they call me`];
How can I check what the closest match is? In this example it should be the first value of my array.
2) The second part is how I can get the name out of the user input. Is it possible to predefine a place where the variable should stand?
Something like this
const nameSentences = [`my name is ${varName}`, `i'm ${varName}`, `they call me ${varName}`];
And afterwards substring the matching sentence with the user input to save the name the variable?
You can save the different ways you would like to accept a name as Regular Expressions, with the capture for the name in the regular expression. You can get as robust as you'd like with it, but here is a starting point.
Once you find a match, you can stop iterating over the possible variations, you can take the match and output the name.
const nameSentences = [
/i'm (\w+)/i,
/my name is (\w+)/i,
/they call me (\w+)/i
];
function learnName(input) {
let match;
for (let i = 0; i < nameSentences.length; i++) {
match = input.match(nameSentences[i]);
if (match) break;
}
if (match) {
return `Hello, ${match[1]}. It's nice to meet you.`;
} else {
return `I didn't catch that, would you mind telling me your name again?`;
}
}
console.log(learnName('Hi, my name is Thore.'));
console.log(learnName('They call me Bob.'));
console.log(learnName(`I'm Joe.`));
console.log(learnName(`Gibberish`));

Javascript to verify specific String from textbox

Here what the textbox result looks like,
Please add the following DNS entries
144.68.238.87 name.domain
144.68.238.88 name.domain
144.68.238.89 name.domain
The goal is to validate name.domain by making sure that the user replace name.domain to server name on textbox before submit it. If the user doesn't replace name.domain with their server name, then it will send alert message and return false until user replace it correctly.
Here is my codes,
function DomainValidate() {
var arrayOfLines = document.getElementById('txt').value.split('/n');
arrayOfLines.shift(); //use shift to skip the first line
for (i = 0; i < arrayOfLines.length; i++) {
//somewhere here need to split to get name.domain and then verify it
var domainName = arrayOfLines[i].split(" ", 2);
if(domainName.Equals("name.domain")
{
alert("You must replace name.domain to your new server name");
return false;
}
}
}
I am not sure if these are correct since I couldn't debug the javascript.
First issue I can see is that your character for the newline is incorrect. It should be \n not /n. Second issue I see is that i is a global variable, when it should be local. Third issue is that arrayOfLines[i].split(' ', 2); returns an array, but you are treating it like it returns a string on the next line if (domainName.Equals('name.domain').
With those corrections your code would look more like this:
function domainValidate() {
var arrayOfLines = document.getElementById('txt').value.split('\n');
arrayOfLines.shift(); //use shift to skip the first line
for (var i = 0; i < arrayOfLines.length; i++) {
var line = arrayOfLines[i].trim();
// Grab the second part of the split line, which represents the domain name
var parts = line.split(' ');
var domainName = parts[parts.length - 1];
if (!domainName || domainName === 'name.domain') {
alert("You must replace name.domain to your new server name");
return false;
}
}
}
As far as I can tell without testing, this should work as expected. The best way to test this though is with jsfiddle. Add your html and this script and call it to see if it produces the expected result.
Easiest way that I think
Suppose the id of textbox is domainTxt
src = document.getElementById("domainTxt");
if(verifyInput(src.value)){
//submit your form here
} else
{
return false;
}
function verifyInput(txtVal){
if(txtVal.indexOf("name.domain") >-1){
return false;
}else {
return true;
}
}

jQuery check is letter is available in the array

I still have a problem with jQuery code.
I want to check characters from strings which is in array while user typing something in the input. If any of first one characters is available in the array i want to display "VALID".
var postcodes = ["00-240","80","32","90","91", "8", "11"];
$('input[name="text-391"]').keyup(function(){
var val = this.value;
var m = $.map(postcodes,function(value,index){
var reg = new RegExp('^'+val+'.*$')
return value.match(reg);
});
if(m.length && val.length) {
$('#error').hide(300);
} else {
$('#error').show(300);
}
});
This code checks that all what user type in the input is in array, but i want to check this letter after letter.
For example:
user types: 0 - it's ok
user types: 00 - it's still ok
user types 00-340 - it's not ok and now I want to display warning that we haven't it in the array
user types: 3 - it's ok
user types: 35 - it's not ok, and now i want to display warning that we haven't it in the array
user types 80-125 - it's still ok [important]
user types 11-1 - it's still ok [important]
I will be very grateful for any tips. Regards
you need to add below code in $.map
if(val.length>2 && val.indexOf("-")>-1 && !(value.indexOf("-")>-1))
val= val.substring(0,val.indexOf("-"))
Here is the working DEMO
Explanation:
You just want to check if enter value length is more than two and it contains - and value in map should not contain -(you need last and condition for letter like "xx-xxx"
Thanks
You'll have to check it both ways:
var m = $.map(postcodes,function(value,index){
var reg = new RegExp('^'+val+'.*$')
var result=value.match(reg);
if (result.length) {
return result;
} else {
reg = new RegExp('^'+value+'.*$')
return val.match(reg);
}
});
You can optimize further if you first create an array of regex's based on postcodes and then reference them by index in the callback function.

Regular Expression: pull part from string. with JS

Hey all im not every good with regexp i was hoping someone could help.
ok so this is the sting "KEY FOUND! [ 57:09:91:40:32:11:00:77:16:80:34:40:91 ]"
And i need to pull "57:09:91:40:32:11:00:77:16:80:34:40:91", now this key can be meany length not just as written here and with or with out the ":"
now the second sting i would like to test and extract is: "[00:00:09] Tested 853 keys (got 179387 IVs)", i would like to pull "00:00:09" and "853" and "179387".
this would be the raw string http://regexr.com?31pcu or http://pastebin.com/eRbnwqn7
this is what im doing now.
var pass = new RegExp('KEY FOUND\!')
var tested = new RegExp('Tested')
var fail = new RegExp('\Failed. Next try with ([0-9]+) IVs')
var data="Look at the link i added"
if (tested.test(data)) {
self.emit('update', mac, {
'keys' : data.split('Tested ')[1].split(' keys ')[0],
'ivs' : data.split('got ')[1].split(' IVs')[0]
});
} else if (pass.test(data)) {
var key = data.split('KEY FOUND! [')[1].split(' ]')[0].split(':').join('');
} else if (fail.test(data)) {
console.log(data);
}
thanks all
Edit:
I have added more the the question to help with the answer
If it is always surrounded by [] then it is simple:
\[([\s\S]*)\]
This will match any characters enclosed by [].
See it in action here.

Categories

Resources