Uppercase first letter of variable value javascript [duplicate] - javascript

This question already has answers here:
How do I make the first letter of a string uppercase in JavaScript?
(96 answers)
Closed 4 years ago.
I am attempting to uppercase the output string of a variable value as follows;
I have tried:
document.getElementById('namePlaceholder').innerHTML = name.value.charAt(0).toUpperCase() + ' is here ';
name.value is a user input so my attempt is to uppercase the first letter of name.
example
name.value = james
preferred outcome James is here.
is there a simple javascript solution for this?

You cannot mutate strings directly as you are trying - you have to create a new string by concatenating the pieces you want:
document.getElementById('namePlaceholder').innerHTML =
name.value.charAt(0).toUpperCase() + // will give you "J"
name.value.slice(1).toLowerCase() + // will give you "ames"
' is here ';
In lay terms, the slice(1) part says "grab everything after the first character". In more technical terms, if you have the name James, you can think of it as a series of letters (not an array, but kinda):
['J', 'a', 'm', 'e', 's'].
You can access individual letters like name[0], which will give you "J" and name[3] which will give you "e". You can then do name.slice(1), which will start at "a" and grab everything after it: "ames". To illustrate further, you could do name.slice(-2) to get the last 2 characters: "es". Or, if you want "me", you can do name.slice(2, 4).

Using substring
document.getElementById('namePlaceholder').innerHTML =
name.value.charAt(0).toUpperCase() +
name.value.substr(1) +
' is here ';
Using Regular Expression:
document.getElementById('namePlaceholder').innerHTML =
name.value.replace(/^\w/, c => c.toUpperCase()); + ' is here ';
exactly similar to the following:
document.getElementById('namePlaceholder').innerHTML =
name.value.replace(/^\w/, function (chr) {
return chr.toUpperCase();
});
+ ' is here ';

Related

Split string to CamelCase words and also uppercase acronymns

Given a string containing CamelCase and also uppercase acronymns e.g. 'ManualABCTask';
How can it be split to a string with a space between all words and acronyms in a less wordy way?
I had the following process:
let initial = 'ManualABCTask'
//Split on single upper case followed by any number of lower case:
.split(/(['A-Z'][a-z]*)/g)
//the returned array includes empty string entries e.g. ["", "", "Manual", "A", "", "B", "", "C","", "Task", ""] so remove these:
.filter(x => x != '');
//When joining the array, the acronymn uppercase single letters have a space e.g. 'Manual A B C Task' so instead, reduce and add space only if array entry has more than one character
let word = initial.reduce((prevVal,currVal) => {
return (currVal.length == 1) ? prevVal + currVal : prevVal + ' ' + currVal + ' ';
}, '');
This does the job on the combinations it needs to e.g:
'ManualABCTask' => 'Manual ABC Task'
'ABCManualTask' => 'ABC Manual Task'
'ABCManualDEFTask' => 'ABC Manual DEF Task'
But it was a lot of code for the job done and surely could be handled in the initial regex.
I was experimenting while writing the question and with a tweak to the regex, got it down to one line, big improvement! So posting anyway with solution.
My regex know how isn't great so this could maybe be improved on still.
I know near to nothing about JavaScript but i had a bash at it:
let initial = 'ManualABCTask'
initial = initial.replace(/([A-Z][a-z]+)/g, ' $1 ').trim();
There 2 groups: starting from head letter with following lowercases, and starting from head letter until next letter isn't lowercase:
find = new RegExp(
"(" +
"[A-Z][a-z]+" + // Group starting from head letter with following lowercases
"|" +
"[A-Z]+(?![a-z])" + // Group with head letters until next letter isn't lowercase:
")",
"g"
)
initial = 'ManualABCTask'.split(find)
As mentioned in post, changed to handle in regex:
initial = 'ManualABCTask'.split(/(['A-Z']{2,99})(['A-Z'][a-z]*)/g).join(' ');
Group any concurrent upper characters with length of 2 to 99 to get the acronyms, and any single upper character followed by any number of lower to get the other words. Join with space.

insert variable via forEach into regex expression [duplicate]

This question already has answers here:
Use dynamic (variable) string as regex pattern in JavaScript
(8 answers)
Closed 4 years ago.
As you can see below, I'm trying to count how many times a character in string J occurs in string S. The only issue is I can't put the argument o in the forEach loop into the regex expression as shown in the console.log.
var numJewelsInStones = function(J, S) {
let jArr = J.split('');
let sArr = S.split('');
jArr.forEach(o=>{
console.log(S.replace(/[^o]/g,"").length);
})
};
numJewelsInStones("aA", "aAAbbbb");
You can create regular expression with constructor function where you pass string parameters:
new RegExp('[^' + o + ']', 'g')
Your replace logic might look like:
S.replace(new RegExp('[^' + o + ']', 'g'), '')

JS Regex for matching specific array increment ignoring string and seperate increment

I have the following input fields with name attributes of:
carousels['components'][0][0][title]
carousels['components'][0][1][title]
carousels['components'][0][2][title]
carousels['components'][1][0][title]
carousels['components'][1][1][title]
carousels['components'][1][2][title]
carousels['components'][2][0][title]
carousels['components'][2][1][title]
carousels['components'][2][2][title]
I am trying to match the final [ number ] eg this part:
carousels['components'][2][THIS][title]
carousels['components'][2][THIS][title]
carousels['components'][2][THIS][title]
While ignoring the rest
Here is my regex pattern:
/(\[[^components\]])+(\[*])/
This affects both of the int's within brackets when I just want the last one. This regex also doesn't recognize the specific requirement of the first array key 'component'
Live regex test here:
http://www.regexpal.com/?fam=94974
If you want to get the last [ + digits + ], you can use
/^.*\[(\d+)\].*$/
See the regex demo
Backtracking will help getting exactly the last occurrence of [digits]. Grab Group 1 value.
var re = /^.*\[(\d+)\].*$/;
var str = 'carousels[\'components\'][0][0][title]\ncarousels[\'components\'][0][1][title]\ncarousels[\'components\'][0][2][title]\n\ncarousels[\'components\'][1][0][title]\ncarousels[\'components\'][1][1][title]\ncarousels[\'components\'][1][2][title]\n\ncarousels[\'components\'][2][0][title]\ncarousels[\'components\'][2][1][title]\ncarousels[\'components\'][2][2][title]';
for (var s of str.split("\n")) {
var res = (m=re.exec(s)) ? m[1] : "";
if (res) {
document.body.innerHTML += s + ": " + res + "<br/>";
}
}
UPDATE:
To get the first [ + digits + ], you need to use lazy matching with the first dot:
/^.*?\[(\d+)\].*$/
^ - Here, the ? will make matching lazy/reluctant
(it will match any 0+ chars other than a newline as few as possible)
See another regex demo.
You can try this
^.*(\[.*?\])\[.*?\]$
<------->
Match in this(1st captured group)
Regex Demo
If you want to match ['components'] exclusively, then you can use
^.*\['components'\].*(\[.*?\])\[.*?\]$

Function to split a phrase of the form "fooBar" into "foo bar" in javascript? [duplicate]

This question already has answers here:
Split by Caps in Javascript
(4 answers)
Closed 8 years ago.
What's the best way to have a function that takes in a phrase of the form fooBar and returns the words foo bar?
My current approach of iterating over all characters to find a capitalized letter and then splitting on that index seems suboptimal is there a better way?
Thanks!
Your approach is the good one, that is exactly what split function does with this pattern: (?=[A-Z])
var resultArray = mystring.split(/(?=[A-Z])/);
The pattern uses a lookahead assertion (?=...) that means followed by.
Note: if you want to make lowercase all items of the result array, you can map the array like this:
resultArray = resultArray.map(function (x){ return x.toLowerCase(); });
The answer here suffices: Split by Caps in Javascript
Basically use a regex that looks for caps and does a split. To be complete the function is
function splitFooBar() {
var fb = fooBar.split(/(?=[A-Z])/);
fbString = fb.length > 1? fb[0] + " " + fb[1].substr(0, 1).toLowerCase() + fb[1].substr(1): fb[0];
return fbString;
}
try this
var re = /([A-Z])/g;
var str = 'fooBar fooBar fooBarww oldWman ';
var subst = ' $1';
var result = str.replace(re, subst);
result = result.toLowerCase();
console.log(result)
alert(result)

Formatting numbers with regex JavaScript [duplicate]

This question already has answers here:
How to format numbers as currency strings
(67 answers)
Closed 9 years ago.
I'm trying to format a number as brazilian currency, but I'm not sure what's going wrong.
function format2(n, currency) {
return currency + " " + n.toFixed(2).replace(^\s*(?:[1-9]\d{0,2}(?:\.\d{3})*|0)(?:,\d{1,2})?$/g, "$1,");
}
Taken from the comments: “but its giving me a syntax error..”
You're missing a slash to define a regex literal. Change your return statement to
return currency + " " + n.toFixed(2).replace(/^\s*(?:[1-9]\d{0,2}(?:\.\d{3})*|0)(?:,\d{1,2})?$/g, "$1,");
^ Teda, the magic opening slash!
Btw, your regex is too complex IMO and doesn't format correctly. I would just do /\./g to get the matching periods, so your replace statement looks like .replace(/\./g, ",");
Demo
I don't know why you're so keen to use a regular expression for this. The following loop solution should be fine and offers a more general solution:
function formatNumber(num, places, thou, point) {
var result = [];
num = Number(num).toFixed(places).split('.');
var m = num[0];
for (var s=m.length%3, i=s?0:1, iLen=m.length/3|0; i<=iLen; i++) {
result.push(m.substr(i? (i-1)*3+s : 0, i? 3 : s));
}
return result.join(thou) + point + num[1];
}
console.log('R$ ' + formatNumber(12345678.155, 2, '.', ',')); // R$ 12.345.678,16
console.log('R$ ' + formatNumber(12.155, 2, '.', ',')); // R$ 12,16

Categories