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 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 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 an answer here:
Why this javascript regex doesn't work?
(1 answer)
Closed 3 years ago.
Trying to replace everything inside brackets [ ] with an element of an array. Example:
function replacingText(){
var names = ["Cole", "Kyle", "Chase"];
var sentance = 'This is [Cole].'
var regex = "\[(.*?)\]/gm";
console.log(sentance.replace(regex, names[1]));
}
So the output should be 'This is Kyle.' instead of 'This is [Cole].'
The only thing that needs fixed is the regex string needs to be
var regex = /\[(.*?)\]/gm;
The /gm on the end just means it wont stop at the first one it finds and the "m" stands for multi-line matching.
The javascript string replace can accept both strings and regular expressions as the first argument. See the examples presented here.
In your case you are passing the first as a string of a regular expression: "\[(.*?)\]"
Instead you should either match the exact string sentence.replace("[Cole]", names[1]) or, what you probably want, is to use the regular expression to match any name sentence.replace(/\[.+\]/g, names[1]) (note that the first argument does not contain any quotes)
The /g (global) is used to match all occurrences in the sentence. Otherwise only the first occurrence would be replaced.
Could you try this :
function replacingText() {
var names = ["Cole", "Kyle", "Chase"];
var sentance = "This is [Cole] [ahmed]";
var regex = /\[([0-9]|[aA-zZ])*\]/g;
console.log(sentance.replace(regex, names[1]));
}
I just tried it and it works as expected
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:
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, '');