How to preserve character case using string.replace()? [duplicate] - javascript

This question already has answers here:
Replace text but keep case
(11 answers)
Closed 2 years ago.
I am attempting to write a function that will replace all of the vowels in a string with another arbitrary vowel which is selected by an end user. So far, I have been able to write a function that will replace all of the vowels regardless of case, but I would like to be able to preserve the case during replace().
Here is an example of what I am doing right now.
var selectedVowel = "a";
var vowels = /[aeiouAEIOU]/gi;
function rep(string){
let newString = string.replace(vowels, selectedVowel);
return newString;
}
rep("FooBar Exe. unIt");
// returns "FaaBar axe. anat"
// Intended output should return "FaaBar Axe. anAt"
I have tried using Regular Expressions to modify the search criteria for replace() and selectedVowel, but I can't figure out how to use the right regex characters to achieve that end.
I have also looked into methods that use split() to replace the first letter of a word, but this method seems to be limited to the string's indexes, which are not known at the time of the function call.
Any suggestions?

String.prototype.replace() takes a function in place of the substitution string, which is called for each match.
You could write a function that checks each match and replaces it with selectedVowel as-is or uppercased, depending on the case of the matched string.
A little trick to check if a character is upper/lowercase is to compare it to the upper/lowercased version of itself, as in match === match.toUpperCase().
var selectedVowel = "a";
var vowels = /[aeiouAEIOU]/gi;
function rep(string){
return string.replace(vowels, match => {
if (match === match.toUpperCase()) {
return selectedVowel.toUpperCase()
}
return selectedVowel
});
}
console.log(rep("FooBar Exe. unIt")) //=> "FaaBar Axa. anAt"

Related

How to remove thousand separaters in number using javascript? [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 2 years ago.
problem:
I want to remove the comma in a string and make it as a number.
It means,
234,345 should become 234345.
1,234 should become 1234
4,567,890 should become 4567890
I have created one code like this.
let a = "5,245"
function numberWithoutCommas(x) {
return x.replace(",","");
}
const b = parseInt(numberWithoutCommas(a))
console.log(typeof(b))
console.log(b)
This is failing when there more comma in the string.It means 1,234,567 gives 1234. So can someone help me to achieve it?
Splitting and joining should do the job
return x.split(',').join('');
You can simply parse to a number and use a regex
const s = ['5,332', '39,322,322,233']
function numberWithoutCommas(x) {
return Number(x.replace(/,/g, ''));
}
for (const a of s) {
const n = numberWithoutCommas(a);
console.log(n, typeof n);
}
passing string as a first argument to replace method will only replace the very first occurrence.
let str = '111,11,11,1';
str.replace(',','') // result:- 11111,11,1
use regex instead
str.replace(/,/g,'') //result:- 11111111
in your use case
function numberWithoutCommas(x) {
return x.replace(/,/g,"");
}
The replace() method searches a string for a specified value, or a
regular expression, and returns a new string where the specified
values are replaced.
Note: If you are replacing a value (and not a regular expression),
only the first instance of the value will be replaced. To replace all
occurrences of a specified value, use the global (g) modifier.
So, to replace all the occurrences of ,, we should rather use /,/g instead of just ,.
Then your code would be something like the following
let a = "1,234,567"
function numberWithoutCommas(x) {
return x.replace(/,/g,"");
}
const b = parseInt(numberWithoutCommas(a))
console.log(typeof(b))
console.log(b)
I hope this helps :)

JavaScript: Can I use the filter function with regular expressions?

I tried to find a similar question to avoid creating a duplicate and I couldn’t, but I apologise if I missed any. I've just started learning how to code and I've encountered this problem:
With JavaScript, I want to use the filter arrays method (https://www.freecodecamp.org/challenges/filter-arrays-with-filter) with a general expression for all non alphanumeric characters.
For example:
var newArray = oldArray.filter(function(val) {
return val !== /[\W_]/g;
});
Can I do that? In the mozilla guide (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) it mentions you can use regular expressions with replace, and I understand how to do that, but it doesn’t mention filter at all.
To put another less abstract example, this is the code I’m working on:
function palindrome(str) {
var splitStr = str.split("");
var filterArray = splitStr.filter(function(val) {
return val !== /[\W_]/g;
});
return filterArray;
}
palindrome("ey*e");
If I’m doing things right so far, the function should return [“e”, “y”, “e”]. But it returns [“e”, “y”, “*”, “e”] (as if I hadn’t filtered it at all). I just wonder if I’ve made a mistake in my code, or if one simply can’t use filter with regular expressions.
If that's the case, why? Why can't one use filter with regular expressions!? Why do we have to use replace instead?
This really isn't an issue relating to .filter(), it's just that you aren't testing your string against your regular expression properly.
To test a string against a regular expression you use the .test() method:
function palindrome(str) {
var splitStr = str.split("");
var filterArray = splitStr.filter(function(val) {
// Test the string against the regular expression
// and test for no match (whole thing is preceeded by !)
return !/[\W_]/g.test(val);
});
return filterArray;
}
console.log(palindrome("ey*e"));
Instead of first splitting the string into chars, and then test every single one of them, why don't you just get all matches for the string?
function palindrome(str) {
return str.match(/[a-zA-Z0-9]/g) || [];
}
let chars = palindrome("ey*e");
console.log(chars);
About the used regex: \W is the same as [^\w] or [^a-zA-Z0-9_]. So, not [\W_] is equivalent to [a-zA-Z0-9].

Use match in replace [duplicate]

This question already has answers here:
Javascript string replace method. Using matches in replacement string
(2 answers)
Closed 3 years ago.
I need to put every non-alphabetic character between spaces.
I want to do this using RegExp, and I understand it enouch to select them all (/(^a-zA-Z )/g).
Is there a way to use the original match inside the replace?
(something like)
str.replace(/(^a-zA-Z )/g,/ \m /);
If not I will just loop over all of them, but I really want to know it it is possible.
Yes. You can give the String.prototype.replace() function a RegExp as it's search. You can also give it a function to handle replacing.
The function will give you the match as the first parameter, and you return what you want to change it to.
const original = 'a1b2c';
const replaced = original.replace(/([^a-z])/gi, match => ` ${match} `);
console.log(replaced);
If you just need to do something simple, you can also just use the $n values ($1, $2, etc) to replace based on the selected group (the sets of parentheses).
const original = 'a1b2c';
const replaced = original.replace(/([^a-z])/gi, ' $1 ');
console.log(replaced);
Yes, it is possible. You can use regex with group:
var text = '2apples!?%$';
var nextText = text.replace(/([^a-zA-Z])/g, ' $1 ');
console.log(nextText);
You can check replace function on this link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Tricky RegEx Capture [duplicate]

This question already has answers here:
My regex is matching too much. How do I make it stop? [duplicate]
(5 answers)
Closed 6 years ago.
I've got a couple strings and I need to pull characters out that appear between double quotes. The problem is, I want to grab them in groups.
var str = 'FF\"J"A4"L"';
var results = str.match(/\"(.*)\"/);
This returns everything between the first and last double quote. In this case it returns J"A4"L but what I need it to return is J and L.
The content between quotes is pretty much any unicode character like letters and numbers including as }, =, and #.
Any ideas on how to complete this with regex?
It sounds like the content between quotes is any character except for a quote, in which case you can get away with
/"([^"]*)"/
what you're looking for is this with the /g "global flag":
/("[^"]*")/g
In your example, it's like this:
var str = 'FF\"J"A4"L"';
var results = str.match(/("[^"]*")/g);
When doing this, results would be [""J"", ""L""], which contains the entire match (which is why the extra quotes are there).
If you wanted just the matched groups (which returns just the groups, not the whole match area), you would use exec:
var str = 'FF\"J"A4"L"';
var results = []
var r = /("[^"]*")/g
match = r.exec(str);
while (match != null) {
results.push(match[1])
match = r.exec(str);
}
Now, results is ["J", "L"]

simple regular expression with equals but dont want to use split [duplicate]

This question already has answers here:
Regular Expressions in JavaScript for URL Capture
(4 answers)
Closed 7 years ago.
I have the message string as follows.
string=052
I need to use regular expression not split.
I want to return everything past the equals. 052
This is what i tried and gives me id=null
var regex = '[^?string=]';
var id2 = mystring.match(regex);
I have tried online regex checkers and it looks like it matches all but the a
is there a better reg ex i should try? id should not equal null.
You're using String.match() incorrectly. Try this:
var regex = '^message=(.*)$';
var id = queryString.match(regex)[1];
.match() returns an array; the first element (at [0]) is the entire matched string, and the second element (at [1]) is the part that's matched in the (first) set of parentheses in the regex.

Categories

Resources