How to format input value on keyDown()? [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 5 years ago.
Improve this question
I would like to force the input value of a text field to comply with a specific format. It needs to be capitalized and with no numbers allowed.
I would like this event to fire on onKeydown().
Examples:
Lionel MESSI => Lionel Messi
LiONEL MesSI => Lionel Messi
Neymar JR => Neymar Jr
Neymar 22 JR => Neymar Jr
Franck D'HONNEUR => Franck D'Honneur
Kevin PEREZ ROBERTO => Kevin Perez Roberto

There is no simple one-liner way of doing this. However, you can make a function which can format the name for you.
Originally taken from this answer, I've modified it slightly to reflect your desired output:
var name1 = "Lionel MESSI";
var name2 = "LiONEL MesSI";
var name3 = "Neymar JR";
var name4 = "Neymar 22 JR";
var name5 = "Franck D'HONNEUR";
var name6 = "Kevin PEREZ ROBERTO";
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}).replace(/[0-9]/g, '');
}
console.log(toTitleCase(name1));
console.log(toTitleCase(name2));
console.log(toTitleCase(name3));
console.log(toTitleCase(name4));
console.log(toTitleCase(name5));
console.log(toTitleCase(name6));
You may want to check out toUpperCase() and toLowerCase() from the MDN documentation.
To get this functionality in on onKeyDown(), you can use jQuery like the snippet below. I do advice against onKeyDown() though as this creates a weird user experience. Try onBlur instead.
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}).replace(/[0-9]/g, '');
}
$("#name").on("keydown", function() {
$(this).val(toTitleCase($(this).val()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Name: <input id="name">

With the help of a little helper function from this question: How do I make the first letter of a string uppercase in JavaScript?
I wrote a quick script that fires on input blur:
$(document).ready(function() {
function capitalizeFirstLetterOfEachWord(string) {
strArr = string.split(' ');
resArr = [];
for(i=0;i<strArr.length;i++){
resArr[i] = strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1);
}
return resArr.join(" ");
}
$('.forceCapital').blur(function(e) {
$(this).val(capitalizeFirstLetterOfEachWord($(this).val()));
});
});
https://jsfiddle.net/sa2ox30d/2/

Related

Parsing String for name value pairs [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
I'm trying to parse this inbound email body_text so that is looks like "Employee Start Date":" 2021/09/07"
I'm trying to put the string through a exReg, but can't get it to format correctly. Any suggestions? I have recently updated my script.
thanks!
Employee Start Date:
2021/09/07
Employee ID:
123456789
Employee Preferred Name:
John Doe
Employee Company:
Global
var emailObj = {};
try {
var valPairs = body_text;
var regEx = /^(.+):(.+)$/; //Name is everything preceding first :, value everything after.
var valPairs = body_text.split("\n").filter(function (item) {
return regEx.test(item);
});
var matches;
//loop through email body and build object
for (var i = 0; i < valPairs.length; i++) {
matches = valPairs[i].match(regEx);
try {
emailObj[matches[1].toString().trim()] = matches[2].toString().trim(); //Add trimmed name/val to object
} catch (ex) {
gs.error(ex.message);
}
}
} catch (ex) {
gs.error(ex.message);
}
console.log(emailObj)
The name value pairs needs to be on on the same line with no line breaks. I need the results to look like this.
Employee Start Date: 2021/09/07
Employee ID: 123456789
Employee Preferred Name: John Doe
Employee Company: Global
thanks in advance!
Here's an example to format the html better. It also parses it from the JSON string into a jS object.
const email = "Employee Start Date:<br> <br> 2021/09/07 <br> <br> Employee ID:<br> <br> 123456789 <br> <br> Employee Preferred Name:<br> <br> John Doe <br> <br> Employee Company: <br> <br> Global<br> <br>"
function extractData(str) {
str = str.replace(/(:\s*(?:<br>\s*)+)/gm, '": "');
str = str.replace(/(\s*(?:<br>\s*)+)/gm, '", "');
str = str.replace(/(,\s*"$)/gm, '}');
str = str.replace(/(^)/gm, '{"');
return JSON.parse(str)
}
console.log(extractData(email))

replace the string from just before the last dot(.) [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 string like A/B/C/D.txt
So I want to replace the character just before the last . with the new one.
Like I would add E in last So the output should be A/B/C/E.txt
Can this is possible with only replace and concat Or Regex should help?
I'm sure the output is correct.
A/B/C/E.txt
var filename = 'A/B/C/D.txt';
var dotIndex = filename.lastIndexOf('.');
document.write(filename.substr(0, dotIndex-1) + 'E'+filename.substr(dotIndex, filename.length-dotIndex));
var parts = 'A/B/C/D.txt'.split('.');
if(parts.length > 1)
{
parts[parts.length-2] = parts[parts.length-2].replace(/.$/,"E");
let result = parts.join('.');
console.log(result);
}
Try this:
let name = "A/B/C/D.txt"
let res = name.substr(0, name.lastIndexOf(".")) + "E." + name.substr(name.lastIndexOf(".") + 1);
console.log(res);

Compare and Remove duplicate part of string [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 4 years ago.
Improve this question
I have a an array of product names like:
Big Bottle 500ml
Big Bottle 1l
Big Bottle 2l
I want to remove the duplicated first part of the string in JavaScript to produce an array like:
500ml
1l
2l
The Product names can be anything i.e. Tub 8oz but will always have duplication/the same prefix at the start
Not sure where to start with this regex or maybe a loop that compares each character until it hits a missmatch
Since you said but will always have duplication at the start so you can try following
Get the string to remove from the first element and then loop through all the elements to remove that string
let arr1 = ['Big Bottle 500ml', 'Big Bottle 1l', 'Big Bottle 2l']
let arr2 = ['Bottle 500ml', 'Bottle 1l', 'Bottle 2l']
function getData(arr) {
let strToRemove = arr[0].match(/\D+/)[0]
return arr.map(d => d.replace(strToRemove, '').trim())
}
console.log(getData(arr1))
console.log(getData(arr2))
If your format will always be Name Name Name ... XXXunit. You can easily split the string with the space delimiter. It doesn't really detect any duplicates, but based on your post, it sounds like youre just trynna get the value and unit
const data = ['Tub 500ml', 'Tub 450ml', 'Small Can 200ml', 'Big Ass Bottle 999ml', 'Artificial Rain Tank V99.55 5500.50L'];
const result = [];
data.forEach(function(item){
const splitted = item.split(" ");
result.push(splitted[splitted.length - 1]);
})
console.log(result)
Using Array#reduce() to walk through all the characters to find the common starting string then map() to remove it
const prods = ['Big Bottle 500ml','Big Bottle 1l','Big Bottle 2l'];
const dupStr = [...prods[0]].reduce((a, c) => {
return prods.every(s => s.startsWith(a + c)) ? a + c : a;
}, '')
const res = prods.map(s => s.replace(dupStr, '').trim())
console.log(`common string :: "${dupStr}"`)
console.log('results ::\n',res)

How to validate postcode in a form using JavaScript [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 7 years ago.
Improve this question
I'm trying to validate a postcode using JavaScript.
I have my regex.
^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})$
This is my function so far, not sure how to implement regex.
function validatePostcode()
{
var postcode = document.getElementById("postcode").value;
}
Any other suggestions that would format a postcode that matches;
CF24 9DG
You can do something like this:
function validatePostalCode(){
var regExp = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})$/;
var postcode = document.getElementById("postcode").value;
if( regExp.test( postcode ) ){
// Do something here, result is true.
} else {
alert("result is false");
}
}
You can try it out in this fiddle: http://jsfiddle.net/Cedriking/5b8wtf1f/2/
You should use JavaScript test() Method RegExpObject.test(string) that returns:
TRUE if the input string matches the RegExpObject regex
FALSE if the input string does not match the RegExpObject regex
Your validator function should look like this:
var validatePostCode = function(postCode) {
var parsePostCode = 'your_regex';
return parsePostCode.test(postCode);
};
var postCode = document.getElementById("postcode").value;
validatePostCode(postCode); // calling the validator function

I can't replace this pattern in javascript [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 need your help on my new project
I hate regular expressions and its rules but i must use it this project.
want do this replace
var aString = '[bkz:sample key]';
I want get into key variable 'sample key' value from this aString
var key,clean;
key = 'sample key';
clean = cleanChars(key);
// clean = sample_key
//my target
key
how can i do this?
thanks in advance
function extractKey(str) {
var match = (str || '').match(/^\[bkz:(.+)\]$/);
return match? match[1] : '';
}
extractKey('[bkz:sample key]'); //sample key
var aString = "[bkz:sample key]";
var regex = /^\[(.+)\:(.+)\]$/;
var matches = regex.exec(aString);
// "sample key" should now be in matches[2]

Categories