Change case using Javascript regex [duplicate] - javascript

This question already has answers here:
Javascript replace() with case-change
(2 answers)
Closed 8 months ago.
How to change case of some backreference in String.replace()? I want to match some part in text and change its case to upper/lower.

You can use a regex for your match then pass a function, here's an example for converting CSS properties:
"margin-top".replace(/-([a-z])/, function(a, l) { return l.toUpperCase(); })
//result = "marginTop"
You can test it out here. This regex takes any -alpha (one character) and turns it into -upperalpha, it's just an example though, any regex works, and you'll want to call .toUpperCase() or .toLowerCase() (or anything else really) on the second argument in the callback, which is the current match.

Just use a case-insensitive regex switch on the pattern that you wish to replace.
Something like:
myString.replace(/AnyCasE/gi, "anycase")

Related

Replace specific parameters [duplicate]

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 g‍lobal 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);
}

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]);
});

Javascript string search double and single quote using RegExp [duplicate]

This question already has answers here:
How do I do a case-insensitive string comparison?
(15 answers)
javascript includes() case insensitive
(11 answers)
Closed 2 years ago.
I'm using the following code to search sub string in a string
mystring.search(new RegExp(substring, 'i'))
Reason why I am using new RegExp is, I want to search case insensitive. However, when there is a string like
var mystring = '10" stick';
and I want to search 10", the code above does not return any result. It's clearly because of new RegExp and double quote. Is there any particular flag that needs to be passed in new RegExp? I googled a lot but couldn't find any solution. What am I missing?
search returns match position, maybe ur confused by this.
So, try this out,
const myString = '10" stick';
console.log(myString.match(new RegExp('10"', 'i'))[0])
console.log(myString.match(new RegExp('ick', 'i'))[0])
console.log(myString.match(new RegExp('asd"', 'i'))) // non-matching
It returns the match or null if theres non. AND it matches 10" in 10" stick
see String.prototype.search mdn

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'

3 Character Long Alphanumeric Regex Not Working [duplicate]

This question already has answers here:
How to detect exact length in regex
(8 answers)
Closed 4 years ago.
So I am trying to use a regular expression to check against strings but it doesn't seem to be working properly.
Basically I want it to match a alpha-numeric string that is exactly 3 characters long. The expression I am using below does not seem to be working for this:
const msg = message.content;
const regex = /[A-Za-z0-9]{3}/g;
if (msg.match(regex)) {
// Do something
}
Am I doing something wrong? Any help would be appreciated. Thanks in advance.
You need to add ^ and $ for the start-of-string anchor and end-of-string anchor, respectively - otherwise, for example, for #123, the 123 will match, and it will pass the regex. You also might consider using the i flag rather than repeat A-Za-z, and you can use \d instead of 0-9.
It looks like you just want to check whether the string passes the regex's test or not, in which case .test (evaluates to a boolean) might be a bit more appropriate than .match. Also, either way, there's no need for the global flag if you're just checking whether a string passes a regex:
const regex = /^[a-z\d]{3}$/i;
if (regex.test(msg)) {
// do something
}

Categories