JavaScript replace regex with array element [duplicate] - javascript

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

Related

Regex match pattern more than once in the same line [duplicate]

This question already has answers here:
Regular expression to stop at first match
(9 answers)
Closed 7 months ago.
I am trying to perform this transformation to a string (using javascript):
Input:
[hello]{world}and[good]{night}
Output:
<span class="top">hello<span class="bottom">world</span></span>and<span class="top">good<span class="bottom">night</span></span>
To do that I am using the following regex:
text.replace(/\[(.*)\]\{(.*)\}/gim, "<span class='top'>$1<span class='bottom'>$2</span></span>")
It works correctly when only setting one occurrence of the pattern in a string [hello]{world}
But if I add a string with more than one, the regex matches the first [] and the last {} instead, and prints this:
<span class='top'>hello]{world}and[good<span class='bottom'>night</span></span>
How can I tell regex to match the first pattern and the second pattern instead of matching it as one bigger pattern?
Note that between the [] and {} I expect there to be no text. So [hello]world and good{night} should not be matched.
You need to put ? after .* to make the quantifier lazy, instead of greedy.
const text = '[hello]{world}and[good]{night}'
const result = text.replace(/\[(.*?)\]\{(.*?)\}/gim, "<span class='top'>$1<span class='bottom'>$2</span></span>")
console.log(result)

JavaScript - replace nth index of regex pattern [duplicate]

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"));

Regex replace all occurrences of text WITH brackets [duplicate]

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.

Why do String.prototype.match() return two elements when string only has one unique match? [duplicate]

This question already has answers here:
match() returns array with two matches when I expect one match
(2 answers)
Closed 5 years ago.
I cant understand why this code snippet return an array on two strings "BEARING" instead of only a string "BEARING. Any ideas?
const cleanedString = "ANGULAR CONTACT (ROLLING) BEARING"
const noun = cleanedString.match(/\b(\w+)$/);
console.log(noun);
You need to use the global /g flag:
const cleanedString = "ANGULAR CONTACT (ROLLING) BEARING"
const noun = cleanedString.match(/\b(\w+)$/g);
console.log(noun);
From String.prototype.match() [MDN]:
If the regular expression does not include the g flag, str.match() will return the same result as RegExp.exec().
It returns an array of 2 which signify
Full Match of the string
String matched in the first capturing group
You can make it a non capturing group by
const cleanedString = "ANGULAR CONTACT (ROLLING) BEARING"
const noun = cleanedString.match(/\b(?:\w+)$/);
console.log(noun);
where ?: signifies that the group would be non capturing
By default match returns the string that matched as the first value.
By putting parens in your regex, you asked for a part of the matched string to be returned (which happens to be the same in this case).
So if your regex had been this:
/^(\w+).*\b(\w+)$/
You would have 3 strings returned
The whole string
ANGULAR
BEARING

Why are characters outside my capturing parentheses included in matches from my RegExp? [duplicate]

This question already has answers here:
How do you access the matched groups in a JavaScript regular expression?
(23 answers)
Closed 6 years ago.
Working in JavaScript I have strings that might contain words prefixed by an "#". The string might look like this #one two #three. I want a RegExp that finds the words prefixed by the "#" but I don't want to include the "#" itself.
I created a RegExp looking like this /#(\w+)/g but when I match it against my strings the "#" is indeed included. Why is this? I assumed that if I wanted to include it then the "#" would be inside the capturing parentheses like this /(#\w+)/g
var s = '#one two #three'
var matches = s.match(/#(\w+)/g)
// matches is now [ '#one', '#three' ] but I want [ 'one', 'three' ]
Note with the result I currently get, there is of course no problem in getting the array I want, I can just remove the first character of each string. But what I want to know is:
Is it possible to change my RegExp to get the desired result?
And:
Why are characters outside my capturing parenthesis included in the result? I find it intuitive that only the characters inside the parenthesis should be included.
You need to access first capturing group
var re = /#(\w+)/gm;
var str = '#one two #three';
var m;
while ((m = re.exec(str)) !== null) {
print(m[1]);
}
Ideone Demo
JS Demo
var re = /#(\w+)/;
var arr = ['#one', 'two', '#three'];
arr.forEach(function(str) {
if (str.match(re))
document.writeln(str.match(re)[1] + '<br>');
});

Categories