Replace any of several characters with underscore [duplicate] - javascript

This question already has answers here:
Replace special characters in a string with _ (underscore)
(2 answers)
Closed 1 year ago.
I have a simple task but I'm not sure of the syntax.
I have a string and want to replace any occurrences of '[', ']', or '.' with an underscore ('_').
I know that string.replace() supports regular expressions, which also give special treatment to [ and ].

Use replaceAll for that
** Note, replace will also work since this a global search.
const src = '/[[\].]/g';
const target = '_';
const formated = string.replaceAll(src, target);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll

Escape the characters with special treatment with backslash.
string = string.replace(/[[\].]/g, '_');
Note that [ and . don't receive special treatment inside [].

Related

How to ignore brackets in a regex [duplicate]

This question already has an answer here:
Escape string for use in Javascript regex [duplicate]
(1 answer)
Closed 3 years ago.
I have a regex that takes a template literal and then matches it against a CSV of conditions and links.
const regex = new RegExp(`^${condition},\/.+`, 'gi');
For example, the variable Sore throat would match
'Sore throat,/conditions/sore-throat/'
I've come across an issue where the template literal might contain brackets and therefore the regex no longer matches. So Diabetes (type 1) doesn't match
'Diabetes (type 1),/conditions/type-1-diabetes/'
I've tried removing the brackets and it's contents from the template literal but there are some cases where the brackets aren't always at the end of the string. Such as, Lactate dehydrogenase (LDH) test
'Lactate dehydrogenase (LDH) test,/conditions/ldh-test/'
I'm not too familiar with regex so apologies if this is simple but I haven't been able to find a way to escape the brackets without knowing exactly where they will be in the string, which in my case isn't possible.
You are trying to use a variable that might contain special characters as part of a regex string, but you /don't/ want those special characters to be interpreted using their "regex" meaning. I'm not aware of any native way to do this in Javascript regex - in Perl, you would use \Q${condition}\E, but that doesn't seem to be supported.
Instead, you should escape your condition variable before passing it into the regex, using a function like this one:
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

How can I replace every regex match with itself and some concatenations? [duplicate]

This question already has answers here:
Using $0 to refer to entire match in Javascript's String.replace
(2 answers)
Closed 3 years ago.
I have a console output that is a string {x:0,y:0,width:1920,height:1080} and need to convert it to object but I can't JSON.parse() it until all properties are surounded by quotes.
I managed to find this regex expression that will match with any word: \b[\w]+\b but I don't know how to use every match to replace '"' + match + '"' on both sides. I realized there are also numbers in there so maybe this would be a better regex: \b[a-zA-Z]+\b provided that property names never include numbers.
Use a group (i.e.: enclose the pattern with ( and )) and access it with $1:
var out = "{x:0,y:0,WIDTH:1920,hEiGhT:1080}";
var rgx = /\b([a-z]+)\b/gi; // use the flag 'i' to make it case-insensitive
console.log(out.replace(rgx, '"$1"'));

Replace a string containing special characters [duplicate]

This question already has answers here:
What special characters must be escaped in regular expressions?
(13 answers)
Closed 4 years ago.
Trying to replace a string that contains special characters. The purpose of this is to convert the query string into an understandable format for end users.
full string is:
var str = 'active=true^opened_by=6816f79cc0a8016401c5a33be04be441^ORassigned_to!=6816f79cc0a8016401c5a33be04be441^short_descriptionISNOTEMPTY^NQopened_atONToday#javascript:gs.beginningOfToday()#javascript:gs.endOfToday()^EQ';
Specifically the portion after ^NQ, in this example: opened_atONToday#javascript:gs.beginningOfToday()#javascript:gs.endOfToday(). I have split the original string with indexOf(^NQ) and passing the resulting sub-strings to a function. I'm then trying a .replace() as below:
var today = replacementString.replace(/(ONToday#javascript:gs.beginningOfToday()#javascript:gs.endOfToday())/g, ' is today ');
replacementString = today;
I have tried with various combinations of the above line, but have not returned what I am hoping for.
I've had no issues replacing special characters, or strings without special characters, but the combination of the 2 is confusing/frustrating me.
Any suggestions or guidance would be appreciated
You should escape the () to \(\) to match it literally or else it would mean a capturing group. For the match you could also omit the outer parenthesis and you have to escape the dot \. to match it literally.
ONToday#javascript:gs\.beginningOfToday\(\)#javascript:gs\.endOfToday\(\)
var str = 'active=true^opened_by=6816f79cc0a8016401c5a33be04be441^ORassigned_to!=6816f79cc0a8016401c5a33be04be441^short_descriptionISNOTEMPTY^NQopened_atONToday#javascript:gs.beginningOfToday()#javascript:gs.endOfToday()^EQ';
var today = str.replace(/ONToday#javascript:gs\.beginningOfToday\(\)#javascript:gs\.endOfToday\(\)/g, ' is today ');
replacementString = today;
console.log(today);

Replace pattern within string with space [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 7 years ago.
I am getting long string with multiple occurances of pattern './.'. The string has dates as well in a format of dd.mm.yyyy.
First I tried with javascript replace method as:
str.replace('./.', ''). But it replaced only first occurance of './.'
Then I tried another regex which replaces special characters but it didn't work as it replaced '.' within dates as well.
How do I replace multiple occurances of a pattern './.' without affecting any other characters of a string ?
. is a special character in a regexp, it matches any character, you have to escape it.
str.replace(/\.\/\./g, '');
Use this simple pattern:
/\.\/\./g
to find all "./." strings in your text.
Try it :
str.replace(/\.\/\./g, '');
Escape . and d \
Add a g for global
Like this
str = str.replace(/\./\./g, '');

Why have two '\' in Regex? [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Extra backslash needed in PHP regexp pattern
(4 answers)
Regex to replace single backslashes, excluding those followed by certain chars
(3 answers)
Closed 7 years ago.
function trim(str) {
var trimer = new RegExp("(^[\\s\\t\\xa0\\u3000]+)|([\\u3000\\xa0\\s\\t]+\x24)", "g");
return String(str).replace(trimer, "");
}
why have two '\' before 's' and 't'?
and what's this "[\s\t\xa0\u3000]" mean?
You're using a literal string.
In a literal string, the \ character is used to escape some other chars, for example \n (a new line) or \" (a double quote), and it must be escaped itself as \\. So when you want your string to have \s, you must write \\s in your string literal.
Thankfully JavaScript provides a better solution, Regular expression literals:
var trimer = /(^[\s\t\xa0\u3000]+)|([\u3000\xa0\s\t]+\x24)/g
why have two '\' before 's' and 't'?
In regex the \ is an escape which tells regex that a special character follows. Because you are using it in a string literal you need to escape the \ with \.
and what's this "[\s\t\xa0\u3000]" mean?
It means to match one of the following characters:
\s white space.
\t tab character.
\xa0 non breaking space.
\u3000 wide space.
This function is inefficient because each time it is called it is converting a string to a regex and then it is compiling that regex. It would be more efficient to use a Regex literal not a string and compile the regex outside the function like the following:
var trimRegex = /(^[\s\t\xa0\u3000]+)|([\u3000\xa0\s\t]+$)/g;
function trim(str) {
return String(str).replace(trimRegex, "");
}
Further to this \s will match any whitespace which includes tabs, the wide space and the non breaking space so you could simplify the regex to the following:
var trimRegex = /(^\s+)|(\s+$)/g;
Browsers now implement a trim function so you can use this and use a polyfill for older browsers. See this Answer

Categories