Javascript replace doesn't work when it should [duplicate] - javascript

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 7 years ago.
var src = "http://blah.com/SOMETHING.jpg";
src.replace(/.*([A-Z])\.jpg$/g, "X");
at this point, shouldn't src be:
http://blah.com/SOMETHINX.jpg
If I use match() with the same regular expression, it says it matched. Regex Coach also shows a match on the character "G".

Try
src = src.replace(/.*([A-Z])\.jpg$/g, "X");
String#replace isn't a mutator method; it returns a new string with the modification.
EDIT: Separately, I don't think that regexp is exactly what you want. It says "any number of any character" followed by a captured group of one character A-Z followed by ".jpg" at the end of the string. src becomes simply "X".

The replace function doesn't change src.
I think what you want to do is:
src = src.replace(/.*([A-Z])\.jpg$/g, "X");

src.replace will replace the entire match "http://blah.com/SOMETHING.jpg", not just the part you captured with brackets.

Related

How to use RegEx in JavaScript replace function [duplicate]

This question already has an answer here:
javascript regexp replace not working, but string replace works
(1 answer)
Closed 1 year ago.
Hello team I am new to JS so I am trying to use RegEx with replacing to take input from the user and replace it if it doesn't match the RegEx I have to be able to put 7 digits or 6 digits followed with one letter currently I am doing this
someID.replace('^(([0-9]{1,7})|([0-9]{1,6}[a-zA-Z]{1}))$')
I am not able to replace the current string with the RegEx expression if I enter
12345678900 it remain the same in that situation I need to be 1234567 after the replace or if I have 12345678asd to be 123456a. How can I achieve that by only replace function and a RegEx expresion
You need to use a different regex and a dirrent replace function.
You will also need to get rid of $ if you want to be able to successfully match the string, without worrying about how it ends.
const sampleIDs = [
"123456789000",
"123456abc",
];
sampleIDs.forEach(id => {
const clean = id.match(/^\d{6}[\d\D]/);
console.log(clean[0]);
});

How to change word to be uppercase in string and keep the rest? [duplicate]

This question already has answers here:
Replace a Regex capture group with uppercase in Javascript
(7 answers)
Closed 3 years ago.
How to change word to be uppercase in string?
for example I have this string: \u001b[31merror\u001b[39m and if the error word is exist then I want to make her uppercase, so the output should be: \u001b[31mERROR\u001b[39m.
Why when I use regex it will not work? \u001b[31merror\u001b[39m.replace( /(error)/, "$1".toUpperCase())
error can be any lowercase word
It doesn't work because the toUpperCase() is applied at the string "$1" and then the result of that operation i passed as second argument of the replace method; you instead expect that toUpperCase is called with the value found. To do so, you need to pass a function as second argument of replace:
"\u001b[31merror\u001b[39m".replace(/(error)/, $1 => $1.toUpperCase())
That would work (notice, $1 here is just an arbitrary variable name, you can call it as you want).
However, since you said that error is just an example, you could either list all the possible values:
mystring.replace(/(error|info|warning)/, $1 => $1.toUpperCase())
Or just replace everything is between \u001b[31m and \u001b[39m (assuming they don't change):
const mystring = `\u001b[31merror\u001b[39m`;
console.log(
mystring.replace(/\u001b\[31m(.*)\u001b\[39m/, $1 => $1.toUpperCase())
);
Hope it helps.
Use this
'\u001b[31merror\u001b[39m'.replace(/(error)/, RegExp.$1.toUpperCase())
This will replace the string 'error' and change it to 'ERROR'

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.

Replace '-' with '--' in a JavaScript string [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I am trying to replace a single dash '-' character in a string with double dashes.
2015–09–01T16:00:00.000Z
to be
2015-–09-–01T16:00:00.000Z
This is the code I am using but it doesn't seem to be working:
var temp = '2015–09–01T16:00:00.000Z'
temp.replace(/-/g,'--')
In JavaScript Strings are immutable. So, when you modify a string, a new string object will be created with the modification.
In your case, the replace has replaced the characters but returns a new string. You need to store that in a variable to use it.
For example,
var temp = '2015–09–01T16:00:00.000Z';
temp = temp.replace(/–/g,'--');
Note The string which you have shown in the question, when copied, I realised that it is a different character but looks similar to – and it is not the same as hyphen (-). The character codes for those characters are as follows
console.log('–'.charCodeAt(0));
// 8211: en dash
console.log('-'.charCodeAt(0));
// 45: hyphen
The hyphen character – you have in the string is different from the one you have in the RegExp -. Even though they look alike, they are different characters.
The correct RegExp in this case is temp.replace(/–/g,'--')
Probably the easiest thing would be to just use split and join.
var temp = '2015–09–01T16:00:00.000Z'.split("-").join("--");

Javascript replace() only replaces first match [duplicate]

This question already exists:
Javascript multiple replace [duplicate]
Closed 9 years ago.
Hello see the jsfiddle here : http://jsfiddle.net/moolood/jU9QY/
var toto = 'bien_address_1=&bien_cp_1=&bien_ville_1=';
var tata = toto.replace('&','<br/>');
$('#test').append(tata);
Why Jquery in my exemple only found one '&' and replace it?
Because that's how replace works in JavaScript. If the search argument is a string, only the first match is replaced.
To do a global replace, you have to use a regular expression with the "global" (g) flag:
var tata = toto.replace(/&/g,'<br/>');
The code that you have written will only replace the first instance of the string.
Use Regex along with g will replace all the instances of the string.
toto.replace(/&/g,'<br/>');

Categories