This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 3 years ago.
I have this
var date = $('#Date').val();
this get the value in the textbox what would look like this
12/31/2009
Now I do this on it
var id = 'c_' + date.replace("/", '');
and the result is
c_1231/2009
It misses the last '/' I don't understand why though.
You need to set the g flag to replace globally:
date.replace(new RegExp("/", "g"), '')
// or
date.replace(/\//g, '')
Otherwise only the first occurrence will be replaced.
Unlike the C#/.NET class library (and most other sensible languages), when you pass a String in as the string-to-match argument to the string.replace method, it doesn't do a string replace. It converts the string to a RegExp and does a regex substitution. As Gumbo explains, a regex substitution requires the global flag, which is not on by default, to replace all matches in one go.
If you want a real string-based replace — for example because the match-string is dynamic and might contain characters that have a special meaning in regexen — the JavaScript idiom for that is:
var id= 'c_'+date.split('/').join('');
You can use:
String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
return this.toString();
}
return this.split(search).join(replace);
}
Related
This question already has an answer here:
Using regex to replace only the last occurrence of a pattern with JS
(1 answer)
Closed 2 years ago.
Suppose I have a regex expression in Javascript, how can I use the replace function to only replace the nth index of regex pattern.
For example suppose this is the target string:
var string = `if ($exampl123 == 'test13')
$example = 'test.testeg.hi';
if ($exampl123 == 'test23')
$example = 'test.testeg.hi';`
The following expression matches the 'test.testeg.hi' part of the string (Matches the two spots where this string is visible).
var deriveString = new RegExp (/test\.\w+\.hi';(?!.*test\.\w+\.hi';)/gm);
In this situation, I would only want to replace the last occurence of this string. If I use the string.prototype.match function, It returns an array of all the matches which is ['test.testeg.hi' , 'test.testeg.hi']
In this case, I would want to only replace the second occurrence of the pattern.
Is there anyway to use the javascript replace function to only replace the last occurrence of the pattern?
Something that allows some sort of way to access the index of the match to replace?
Something like this?
string = string.replace(deriveString[matchedArray.length - 1] , 'insert new text here')
You should then remove the g option from your regex, and aim directly for the final match. This you can do with a greedy (.*) in front of it, and then reproduce that (long) prefix again in the replacement -- using $1.
var string = `if ($exampl123 == 'test13')
$example = 'test.testeg.hi';
if ($exampl123 == 'test23')
$example = 'test.testeg.hi';`
var regex = new RegExp (/(.*)test\.\w+\.hi/s);
console.log(string.replace(regex, "$1insert new text here"));
This question already has answers here:
Javascript/regex: Remove text between square brackets
(4 answers)
Closed 5 months ago.
In short i need to replace every occurrence of text betweeen brackets including the brackets in a string, and the text to be replaced will be in a variable in Javascript.
A simple regex in a replace method wont work because of the brackets.
Example, replace "[test] [teste] test [hello]" with a variable with the value of "hi".
Output: "hi hi test [hello]"
"[test] [teste] test".replace(/\[.*?\]/g, 'hi')
escape the brackets with "\" and use g flag
edit: removed the i flag and chnaged w to . to handle anything inside brackets
I'm not quite sure what you're looking for but .match will store off the matches in an array and .replace will perform the replace for you.
const regex = /\[.*?\]/g;
var mutable = "[test] [teste] test";
const matches = mutable.match(regex); // Save all matches to an array
mutable = mutable.replace(regex, 'dude'); // Replace matches
console.log(mutable);
console.log(matches);
So, the way i found to do it was to get my variable to be replaced, example:
var test= "[test]",
Then i replaced the brackets in it so it would become "\[test\]", then i used:
var regex = new RegExp(test+"+","gm")
then i used this regex in JS replace method.
This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 3 years ago.
I have this
var date = $('#Date').val();
this get the value in the textbox what would look like this
12/31/2009
Now I do this on it
var id = 'c_' + date.replace("/", '');
and the result is
c_1231/2009
It misses the last '/' I don't understand why though.
You need to set the g flag to replace globally:
date.replace(new RegExp("/", "g"), '')
// or
date.replace(/\//g, '')
Otherwise only the first occurrence will be replaced.
Unlike the C#/.NET class library (and most other sensible languages), when you pass a String in as the string-to-match argument to the string.replace method, it doesn't do a string replace. It converts the string to a RegExp and does a regex substitution. As Gumbo explains, a regex substitution requires the global flag, which is not on by default, to replace all matches in one go.
If you want a real string-based replace — for example because the match-string is dynamic and might contain characters that have a special meaning in regexen — the JavaScript idiom for that is:
var id= 'c_'+date.split('/').join('');
You can use:
String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
return this.toString();
}
return this.split(search).join(replace);
}
This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I'm trying to further my understanding of regular expressions in JavaScript.
So I have a form that allows a user to provide any string of characters. I'd like to take that string and remove any character that isn't a number, parenthesis, +, -, *, /, or ^. I'm trying to write a negating regex to grab anything that isn't valid and remove it. So far the code concerning this issue looks like this:
var pattern = /[^-\+\(\)\*\/\^0-9]*/g;
function validate (form) {
var string = form.input.value;
string.replace(pattern, '');
alert(string);
};
This regex works as intended on http://www.infobyip.com/regularexpressioncalculator.php regex tester, but always alerts with the exact string I supply without making any changes in the calculator. Any advice or pointers would be greatly appreciated.
The replace method doesn't modify the string. It creates a new string with the result of the replacement and returns it. You need to assign the result of the replacement back to the variable:
string = string.replace(pattern, '');
This question already has answers here:
Javascript replace() with case-change
(2 answers)
Closed 8 months ago.
How to change case of some backreference in String.replace()? I want to match some part in text and change its case to upper/lower.
You can use a regex for your match then pass a function, here's an example for converting CSS properties:
"margin-top".replace(/-([a-z])/, function(a, l) { return l.toUpperCase(); })
//result = "marginTop"
You can test it out here. This regex takes any -alpha (one character) and turns it into -upperalpha, it's just an example though, any regex works, and you'll want to call .toUpperCase() or .toLowerCase() (or anything else really) on the second argument in the callback, which is the current match.
Just use a case-insensitive regex switch on the pattern that you wish to replace.
Something like:
myString.replace(/AnyCasE/gi, "anycase")