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"));
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:
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 an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 4 years ago.
I'm looking for some assistance with JavaScript/Regex when trying to format a string of text.
I have the following IDs:
00A1234/A12
0A1234/A12
A1234/A12
000A1234/A12
I'm looking for a way that I can trim all of these down to 1234/A12. In essence, it should find the first letter from the left, and remove it and any preceding numbers so the final format should be 0000/A00 or 0000/AA00.
Is there an efficient way this can be acheived by Javascript? I'm looking at Regex at the moment.
Instead of focussing on what you want to strip, look at what you want to get:
/\d{4}\/[A-Z]{1,2}\d{2}/
var str = 'fdfhfjkqhfjAZEA0123/A45GHJqffhdlh';
match = str.match(/\d{4}\/[A-Z]{1,2}\d{2}/);
if (match) console.log(match[0]);
You could seach for leading digits and a following letter.
var data = ['00A1234/A12', '0A1234/A12', 'A1234/A12', '000A1234/A12'],
regex = /^\d*[a-z]/gi;
data.forEach(s => console.log(s.replace(regex, '')));
Or you could use String#slice for the last 8 characters.
var data = ['00A1234/A12', '0A1234/A12', 'A1234/A12', '000A1234/A12'];
data.forEach(s => console.log(s.slice(-8)));
You could use this function. Using regex find the first letter, then make a substring starting after that index.
function getCode(s){
var firstChar = s.match('[a-zA-Z]');
return s.substr(s.indexOf(firstChar)+1)
}
getCode("00A1234/A12");
getCode("0A1234/A12");
getCode("A1234/A12");
getCode("000A1234/A12");
A regex such as this will capture all of your examples, with a numbered capture group for the bit you're interested in
[0-9]*[A-Z]([0-9]{4}/[A-Z]{1,2}[0-9]{2})
var input = ["00A1234/A12","0A1234/A12","A1234/A12","000A1234/A12"];
var re = new RegExp("[0-9]*[A-Z]([0-9]{4}/[A-Z]{1,2}[0-9]{2})");
input.forEach(function(x){
console.log(re.exec(x)[1])
});
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);
}