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.
Related
This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 1 year ago.
I'm trying to replace every instance of ® on every page with <sup>®</sup> but I can't seem to hit every single one. I currently have:
$(document).ready(function(){
var replaced = $('body').html().replace('®','<sup>®</sup>');
$('body').html(replaced);
});
but it's only replacing the first occurance of the ®. How can I get it to do all of them?
I think you should use replaceAll function
var replaced = $('body').html().replaceAll('®','<sup>®</sup>');
The difference between replaceAll() and replace():
If search argument is a string, replaceAll() replaces all occurrences of search with replaceWith , while replace() only the first occurence.
If search argument is a non-global regular expression, then replaceAll() throws a TypeError exception.
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.
This question already has answers here:
Create RegExps on the fly using string variables
(6 answers)
Closed 4 years ago.
I have a regex when I instantiate the Regex object like this:
this.checkRegex = new RegExp(/^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$/);
It works fine, however If I store the regex in string it does not work:
private checkReg: string = '/^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$/';
this.checkRegex = new RegExp(this.checkReg);
I am using angular-typescript. What is the thing I am missing here when I am trying to instantiate by throwing string inside the constructor. Code sample will be really appreciated. Thanks for your help.
When you are passing a string to the RegExp constructor, you need to change it a little bit. Instead of
'/^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$/'
You would omit the preceding and trailing slash
'^([0|\\[+][0-9]{0,5})?([1-9][0-9]{0,15})$'
Note also double escaping the back slash.
If you want to store the RegExp as a String, store it without the forward slashes at the front and back. When creating the RegExp object, those get escaped:
new RegExp('/^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$/');
will result in
/\/^([0|[+][0-9]{0,5})?([1-9][0-9]{0,15})$\//
while,
new RegExp('^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$');
will work:
/^([0|[+][0-9]{0,5})?([1-9][0-9]{0,15})$/
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.
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¬interesting=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¬interesting=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¬interesting=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.