replace in javascript with case conversion - javascript

I want to make the first character of every word in a string to uppercase.
i am referring to this article Replacement Text Case Conversion.
when i am running the regular expression ([a-zA-Z])([a-zA-Z](\s)) with the replacement text as \u$1\l$2 in my editor (sublime text) it works fine.
However, when i am trying to do the same in javascript using replace method as below, its giving syntax errors and hence fails.
var regex = /([a-zA-Z])([a-zA-Z]*(\s)*)/gi;
var rep = "\\u$1\\l$2"; // here it is giving error
var result = input.replace(regex,rep);
How to resolve this?
I know this problem can be solved using charAt() and toUppercase() method. but I want to do it using regex with replace. :)

JS regex engine does not support lower- and uppercasing operators \u and \l in the replacement patterns. Use a callback inside String#replace:
var input = "aZ";
var regex = /([a-zA-Z])([a-zA-Z]*(\s)*)/gi;
var result = input.replace(regex, function($0,$1,$2,$3) {
return $1.toUpperCase() + $2.toLowerCase();
});
console.log(result);
Note that you can reduce your pattern to /([a-z])([a-z]*\s*)/gi.

Related

Javascipt regex to get string between two characters except escaped without lookbehind

I am looking for a specific javascript regex without the new lookahead/lookbehind features of Javascript 2018 that allows me to select text between two asterisk signs but ignores escaped characters.
In the following example only the text "test" and the included escaped characters are supposed to be selected according the rules above:
\*jdjdjdfdf*test*dfsdf\*adfasdasdasd*test**test\**sd* (Selected: "test", "test", "test\*")
During my research I found this solution Regex, everything between two characters except escaped characters /(?<!\\)(%.*?(?<!\\)%)/ but it uses negative lookbehinds which is supported in javascript 2018 but I need to support IE11 as well, so this solution doesn't work for me.
Then i found another approach which is almost getting there for me here: Javascript: negative lookbehind equivalent?. I altered the answer of Kamil Szot to fit my needs: ((?!([\\])).|^)(\*.*?((?!([\\])).|^)\*) Unfortuantely it doesn't work when two asterisks ** are in a row.
I have already invested a lot of hours and can't seem to get it right, any help is appreciated!
An example with what i have so far is here: https://www.regexpal.com/?fam=117350
I need to use the regexp in a string.replace call (str.replace(regexp|substr, newSubStr|function); so that I can wrap the found strings with a span element of a specific class.
You can use this regular expression:
(?:\\.|[^*])*\*((?:\\.|[^*])*)\*
Your code should then only take the (only) capture group of each match.
Like this:
var str = "\\*jdjdjdfdf*test*dfsdf\\*adfasdasdasd*test**test\\**sd*";
var regex = /(?:\\.|[^*])*\*((?:\\.|[^*])*)\*/g
var match;
while (match = regex.exec(str)) {
console.log(match[1]);
}
If you need to replace the matches, for instance to wrap the matches in a span tag while also dropping the asterisks, then use two capture groups:
var str = "\\*jdjdjdfdf*test*dfsdf\\*adfasdasdasd*test**test\\**sd*";
var regex = /((?:\\.|[^*])*)\*((?:\\.|[^*])*)\*/g
var result = str.replace(regex, "$1<span>$2</span>");
console.log(result);
One thing to be careful with: when you use string literals in JavaScript tests, escape the backslash (with another backslash). If you don't do that, the string actually will not have a backslash! To really get the backslash in the in-memory string, you need to escape the backslash.
const testStr = `\\*jdjdjdfdf*test*dfsdf\\*adfasdasdasd*test**test\\**sd*`;
const m = testStr.match(/\*(\\.)*t(\\.)*e(\\.)*s(\\.)*t(\\.)*\*/g).map(m => m.substr(1, m.length-2));
console.log(m);
More generic code:
const prepareRegExp = (word, delimiter = '\\*') => {
const escaped = '(\\\\.)*';
return new RegExp([
delimiter,
escaped,
[...word].join(escaped),
escaped,
delimiter
].join``, 'g');
};
const testStr = `\\*jdjdjdfdf*test*dfsdf\\*adfasdasdasd*test**test\\**sd*`;
const m = testStr
.match(prepareRegExp('test'))
.map(m => m.substr(1, m.length-2));
console.log(m);
https://instacode.dev/#Y29uc3QgcHJlcGFyZVJlZ0V4cCA9ICh3b3JkLCBkZWxpbWl0ZXIgPSAnXFwqJykgPT4gewogIGNvbnN0IGVzY2FwZWQgPSAnKFxcXFwuKSonOwogIHJldHVybiBuZXcgUmVnRXhwKFsKICAgIGRlbGltaXRlciwKICAgIGVzY2FwZWQsCiAgICBbLi4ud29yZF0uam9pbihlc2NhcGVkKSwKICAgIGVzY2FwZWQsCiAgICBkZWxpbWl0ZXIKICBdLmpvaW5gYCwgJ2cnKTsKfTsKCmNvbnN0IHRlc3RTdHIgPSBgXFwqamRqZGpkZmRmKnRlc3QqZGZzZGZcXCphZGZhc2Rhc2Rhc2QqdGVzdCoqdGVzdFxcKipzZCpgOwpjb25zdCBtID0gdGVzdFN0cgoJLm1hdGNoKHByZXBhcmVSZWdFeHAoJ3Rlc3QnKSkKCS5tYXAobSA9PiBtLnN1YnN0cigxLCBtLmxlbmd0aC0yKSk7Cgpjb25zb2xlLmxvZyhtKTs=

Using search and replace with regex in javascript

I have a regular expression that I have been using in notepad++ for search&replace to manipulate some text, and I want to incorporate it into my javascript code. This is the regular expression:
Search
(?-s)(.{150,250}\.(\[\d+\])*)\h+ and replace with \1\r\n\x20\x20\x20
In essence creating new paragraphs for every 150-250 words and indenting them.
This is what I have tried in JavaScript. For a text area <textarea name="textarea1" id="textarea1"></textarea>in the HTML. I have the following JavaScript:
function rep1() {
var re1 = new RegExp('(?-s)(.{150,250}\.(\[\d+\])*)\h+');
var re2 = new RegExp('\1\r\n\x20\x20\x20');
var s = document.getElementById("textarea1").value;
s = string.replace(re1, re2);
document.getElementById("textarea1").value = s;
}
I have also tried placing the regular expressions directly as arguments for string.replace() but that doesn't work either. Any ideas what I'm doing wrong?
Several issues:
JavaScript does not support (?-s). You would need to add modifiers separately. However, this is the default setting in JavaScript, so you can just leave it out. If it was your intention to let . also match line breaks, then use [^] instead of . in JavaScript regexes.
JavaScript does not support \h -- the horizontal white space. Instead you could use [^\S\r\n].
When passing a string literal to new RegExp be aware that backslashes are escape characters for the string literal notation, so they will not end up in the regex. So either double them, or else use JavaScript's regex literal notation
In JavaScript replace will only replace the first occurrence unless you provided the g modifier to the regular expression.
The replacement (second argument to replace) should not be a regex. It should be a string, so don't apply new RegExp to it.
The backreferences in the replacement string should be of the $1 format. JavaScript does not support \1 there.
You reference string where you really want to reference s.
This should work:
function rep1() {
var re1 = /(.{150,250}\.(\[\d+\])*)[^\S\r\n]+/g;
var re2 = '$1\r\n\x20\x20\x20';
var s = document.getElementById("textarea1").value;
s = s.replace(re1, re2);
document.getElementById("textarea1").value = s;
}

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].

Replace with value '$' does not work in javascript

i tried to replace a string, provided the string regex with a value that has $ in the end.
Can anyone tell me what is happening in
Looking into mdn string replace docs, i found it is expected.
But what should one do he want to ignore this.
Means i want the replacing value should get as it is replaced, with 4 $s here.
You need to double the dollars in the replacement pattern as $$ are actually $.
.replace(/{{one}}/g, '000$$$$$$$$')
See String#replace help:
Pattern Inserts
$$ Inserts a "$".
If a user types $ in the replacement (that is, in case it is user-defined) you can just double it:
var ptrn = "{{one}}"; // regex pattern from user input
var repl = "000$$$$"; // replacement from user input
var rx = RegExp(ptrn, "g"); // building a dynamic regex
document.write("pp{{one}}pp".replace(rx, repl.replace(/\$/g, '$$$$')));
// ^--- doubling $s-----^

assign matched values from jquery regex match to string variable

I am doing it wrong. I know.
I want to assign the matched text that is the result of a regex to a string var.
basically the regex is supposed to pull out anything in between two colons
so blah:xx:blahdeeblah
would result in xx
var matchedString= $(current).match('[^.:]+):(.*?):([^.:]+');
alert(matchedString);
I am looking to get this to put the xx in my matchedString variable.
I checked the jquery docs and they say that match should return an array. (string char array?)
When I run this nothing happens, No errors in the console but I tested the regex and it works outside of js. I am starting to think I am just doing the regex wrong or I am completely not getting how the match function works altogether
I checked the jquery docs and they say that match should return an array.
No such method exists for jQuery. match is a standard javascript method of a string. So using your example, this might be
var str = "blah:xx:blahdeeblah";
var matchedString = str.match(/([^.:]+):(.*?):([^.:]+)/);
alert(matchedString[2]);
// -> "xx"
However, you really don't need a regular expression for this. You can use another string method, split() to divide the string into an array of strings using a separator:
var str = "blah:xx:blahdeeblah";
var matchedString = str.split(":"); // split on the : character
alert(matchedString[1]);
// -> "xx"
String.match
String.split

Categories

Resources