Javascript toUpperCase() method [duplicate] - javascript

This question already has answers here:
toUpperCase() is not making the string upper case
(9 answers)
Closed 2 years ago.
I'm brand new to Javascript and have a question on the toUpperCase() method:
let firstName = prompt("Please enter your first name.")
If I wanted to output statement above to upper case, I use the toUpeprCase() method:
firstName = firstName.toUpperCase();
However, if I simply wrote the below code and do not re-assign firstName like in above, then first name doesn't turn to upper case:
firstName.toUpperCase();
Why is it that I need to "re-assign" firstName in order for it to turn upper case? It is very hard to remember this because logically, you'd think just writing firstName.toUpperCase(); would do the trick.
Thank you

.toUpperCase() returns the string value converted to uppercase, so, you need to reassign it.

The toUpperCase() method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one).
So you should reassign the value to the variable to override the previous value
This could be usefull if you want to keep the original value, for example:
const string = 'Hello, I\'m an example!';
const upper = string.toUpperCase();
console.log(string);
console.log(upper);

The .toUpperCase() method is a method of string which returns the uppercase version of given string. It does not modify the existing string. Thus you need to reassign it. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase.

Related

Characters used in string? [duplicate]

This question already has answers here:
Find the characters in a string which are not duplicated
(29 answers)
Closed 1 year ago.
I found many question about counting characters used in a string and solutions
but how can I get all character used in string? Im new to JavaScript, im do not know to output this
for example
"English-Language" to "E,n,g,l,i,s,h,-,L,a,u,e" or "Javascript String" to "J,a,v,s,c,r,i,p,t, ,S,n,g"
Thank you..
Very simple with Set: (just cast it back to an array)
console.log([...new Set("English-Language")]);
console.log([...new Set("Javascript String")]);
And if you want it as a single string, do this:
console.log([...new Set("English-Language")].join(","));
console.log([...new Set("Javascript String")].join(","));
You can use the split function and the Set class to achieve this like so.
new Set("Javascript String".split(''))
The split('') part splits the string using an empty string as the seperator, so it just returns an array of all the characters. If you make a set from that array, it'll remove the duplicates. You can even pass the string directly to the Set constructor. If you want it as an array, just use Array.from.
you can simply use str.split("");
const str = 'English-Language';
str.split("");
Let me know if you face any future issue.
or Second option is
console.log([...new Set("English-Language")]);

How to change word to be uppercase in string and keep the rest? [duplicate]

This question already has answers here:
Replace a Regex capture group with uppercase in Javascript
(7 answers)
Closed 3 years ago.
How to change word to be uppercase in string?
for example I have this string: \u001b[31merror\u001b[39m and if the error word is exist then I want to make her uppercase, so the output should be: \u001b[31mERROR\u001b[39m.
Why when I use regex it will not work? \u001b[31merror\u001b[39m.replace( /(error)/, "$1".toUpperCase())
error can be any lowercase word
It doesn't work because the toUpperCase() is applied at the string "$1" and then the result of that operation i passed as second argument of the replace method; you instead expect that toUpperCase is called with the value found. To do so, you need to pass a function as second argument of replace:
"\u001b[31merror\u001b[39m".replace(/(error)/, $1 => $1.toUpperCase())
That would work (notice, $1 here is just an arbitrary variable name, you can call it as you want).
However, since you said that error is just an example, you could either list all the possible values:
mystring.replace(/(error|info|warning)/, $1 => $1.toUpperCase())
Or just replace everything is between \u001b[31m and \u001b[39m (assuming they don't change):
const mystring = `\u001b[31merror\u001b[39m`;
console.log(
mystring.replace(/\u001b\[31m(.*)\u001b\[39m/, $1 => $1.toUpperCase())
);
Hope it helps.
Use this
'\u001b[31merror\u001b[39m'.replace(/(error)/, RegExp.$1.toUpperCase())
This will replace the string 'error' and change it to 'ERROR'

Escape quotes on string javascript [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I have a variable with this kind of string: 4.5"x8.5"x0.5"
I found many answers about how to escape the quotes, so I write this function:
function replaceQuotesChars (str)
{
var s = str.trim();
// s.replace('"','"');
// s.replace('"','\\"');
// s.replace(/\"/g,'\\"');
s.replace(/\"/g,'"');
return s;
};
But none of those help me to escape the quotes because I get the same string that I submit to the function.
I save that variable with a stringify object to the database so when I parse back the string I get an error.
What I'm doing wrong? Please help me.
After a .replace (or really just about any other string manipulation method) a new string is returned because strings are "immutable" objects (can't be modified once created). Your code assumes the operation happens "in-place". You need to capture the new string (which incidentally, you did do with the .trim() operation).
In the following code:
First .trim() is called on str, which copies the string in str but without the leading and trailing spaces, and then returns that new string.
On that new string, .replace() is called, which copies the trimmed string, but with the characters replaced and then returns a new string.
That final string is what is then returned by the function.
function replaceQuotesChars (str, delimeter) {
// Each string operation returns a new string. Take that final
// string and return it
return str.trim().replace(/\"/g, delimeter);
};
console.log(replaceQuotesChars('10.5" x 4.75"', """));
console.log(replaceQuotesChars('10.5" x 4.75"', "\'"));
console.log(replaceQuotesChars('10.5" x 4.75"', "\""));
#Scott Marcus has already answered the question but if you are confused using regex(like me) there is an alternate method using the .split() method.
var a = str.split("\"");
var newS=""
for(var i = 0; i<a.length; i++){
if(a[1]!= ""){
newS = newS + a[i];
}
}
return newS;
This runs slower than regex but does the job.

RegEx: Extract GET variable from URL [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 9 years ago.
RegExp gurus, heed my call!
This is probably super simple, but I've painted myself in a mental corner.
Taking a regular URL, split after the ?, which gives a string like variable=val&interesting=something&notinteresting=somethingelse I want to extract the value of interesting.
The name of the variable I'm interested in can be a substring of another variable.
So the match should be
either beginning of string or "&" character
followed by "interesting="
followed by the string I want to capture
followed by either another "&" or end of string
I tried something along the lines of
[\^&]interesting=(.*)[&$]
but I got nothing...
Update
This is to be run in a Firefox addon on every get request, meaning that jQuery is not available and if possible I would like to avoid the extra string manipulation caused by writing a function.
To me this feels like a generic "extract part of a string with regex" but maybe I'm wrong (RegEx clearly isn't my strong side)
simple solution
var arr = "variable=val&interesting=something&notinteresting=somethingelse".split("&");
for(i in arr) {
var splits = arr[i].split("=");
if(splits[0]=="interesting") alert(splits[1]);
}
also single line match
"variable=val&interesting=something&notinteresting=somethingelse".match(/(?:[&]|^)interesting=((?:[^&]|$)+)/)[1]
function getValue(query)
{
var obj=location.search.slice(1),
array=obj.split('&'),
len=array.length;
for(var k=0;k<len;k++)
{
var elm=array[k].split('=');
if(elm[0]==query)return elm[1];
}
}
This function directly extract the query URL and return the corresponding value if present.
//usage
var get=getValue('interesting');
console.log(get);//something
If you're using the Add-on SDK for Firefox, you can use the url module:
https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/url.html
This is much better than using regex.

Javascript replace() function [duplicate]

This question already has answers here:
Replace function not replacing [duplicate]
(2 answers)
Closed 8 years ago.
This is a simple replace() question - and I can't get it working to replace a substring in the function below.
function linkOnClick(){
var anyNameYouLike = 'some sort of text/string right here';
anyNameYouLike.replace('right','in');
alert(anyNameYouLike)
}
It should return "some sort of text/string in here" but doesn't. What am I doing wrong? I'm fairly new with Javascript (if it isn't obvious...)
anyNameYouLike = anyNameYouLike.replace('right','in');
In javascript, strings are immutable (they are never modified). As such, the .replace() function does not modify the string you call it on. Instead, it returns a new string. So, if you want anyNameYouLike to contain the modified string, you have to assign the result to it like this:
anyNameYouLike = anyNameYouLike.replace('right','in');
For more info, refer to the MDN description of the .replace() method which says this:
Returns a new string with some or all matches of a pattern replaced by
a replacement. The pattern can be a string or a RegExp, and the
replacement can be a string or a function to be called for each match.
And, in the description of the .replace() method, it says this:
This method does not change the String object it is called on. It
simply returns a new string.

Categories