Regex Replace failing, and I can't catch the reason? - javascript

I use this regex patter with .match() and it works as expected. However, trying to make it work with .replace() appears to be failing, and I can't catch the reason. Maybe I need some new eyes..
(function(){
var testRegex = /^\/Monkey\/tooth\d+\/$/g;
var testStr = '/Monkey/tooth8/';
var testMatch = testStr.match(testRegex,'');
var newString = testStr.replace(testRegex,'');
alert(newString);
if(nullCheck(testMatch) == false){alert('false');}else{alert('true');}
})()
I would expect the alert to alert an empty box but it just alerts the the same thing as testStr. What am I missing from this, I ultimately want to get rid of string in the event it exists. Example output
/Monkey/Tooth10/Hello/World => Hello/World
/Monkey/Tooth10/GoodBye/World => GoodBye/World

Remove ^ and $ to avoid whole string match that assert position at start and end of the string respectively.
You can try
\/Monkey\/tooth\d+\/
OR just remove $
^\/Monkey\/tooth\d+\/
Online demo
Sample code: (use i modifier for ignore-case match)
var re = /\/Monkey\/tooth\d+\//gi;
var str = '/Monkey/Tooth10/Hello/World';
var subst = '';
var result = str.replace(re, subst);
var matchedString = str.match(re);
JavaScript String match() Method
The match() method searches a string for a match against a regular expression, and returns the matches, as an Array object.
Note: If the regular expression does not include the g modifier (to perform a global search), the match() method will return only the first match in the string.
This method returns null if no match is found.

Remove quotes from your regex. So instead of var testRegex = '/^\/Monkey\/tooth\d+\/$/g'; use:
var testRegex = /^\/Monkey\/tooth\d+\/$/g;
In Javascript regex literal is not quoted OR else RegExp object is used.

Related

Get replaced characters with javascript regex replace

I am currently replacing all non-letter characters using
var stringwithoutspecialCharacter = "testwordwithpunctiuation.".replace(/[^\w\s!?]/g, '');
The problem is that I do not know which special character will appear (that needs removing). However I do need to be able to access the removed special character after I've run some code with the word without the special character.
Example inputs:
"test".
(temporary)
foo,
Desired output:
['"','test','"',"."]
['(','temporary',')']
['foo',',']
How could this be achieved in javascript?
Edit: To get both valid and invalid characters, change the regular expression
Quick solution is to define an array to collect the matches.
Then pass in a function into your replace() call
var matches = [];
var matcher = function(match, offset, string) {
matches.push(match);
return '';
}
var stringwithoutspecialCharacter = "testwordwithpunctiuation.".replace(/[^\w\s!?]|[\w\s!?]+/g, matcher);
console.log("Matches: " + matches);

JavaScript: String.search() can't search "[]" or "()"

If you try searching strings such as "[]" or "()" using the search() function it doesn't work.
function myFunction() {
var str = "Visit []W3Schools!";
var n = str.search("[]");
document.getElementById("demo").innerHTML = n;
}
You can try on W3Schools at -
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_search
Searching [] returns -1, while searching () returns 0. Always.
Why is that?
String.search uses a RegExp, and converts its argument to one if it isn't already. [] and () are special characters to RegExp.
You can directly create a regexp and escape the characters like so:
var n = str.search(/\[\]/);
But if you're searching for a literal string, then you should be using String.indexOf instead.
var n = str.indexOf("[]");
The JavaScript search function takes a regular expression as its argument:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search
In regular expressions, "[" and "(" are special characters.
Try replacing your function with this:
function myFunction() {
var str = "Visit []W3Schools!";
var n = str.search("\\[]");
document.getElementById("demo").innerHTML = n;
}
or better:
var n = str.search(/\[]/);
The '[' special character is escaped. Once that is escaped, the ']' does not need to be escaped because it is only treated special after an unescaped '['.
For more information about regular expressions in JavaScript, look here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
It's because search is expecting a regular expression. If a string is passed, then search will explicitly transform it into a regexp using new RegExp.
Calling it like str.search("[]") is like calling it str.search(/[]/) (nothing in the string matches an empty set so -1 is returned).
And calling it like str.search("()") is like calling it str.search(/()/) (the first empty string "" is found at the index 0).
I recommend looking for the docs on MDN not W3Schools.
Because the search string is a regular-expression and "[]" and "()" are both magic. You need to double-escape them:
str.search("\\[\\]")
Or even better, as ephemient points out:
str.indexOf("[]")

Javascript regex conditional statement when two of same character detected in string

I am trying to find a regular expression that detects when a string has two periods. When this condition has been met, it deletes all the characters up to (and including) the first period.
string:
"abc.def.ghi"
abc. would be removed, and we have:
"def.ghi"
I've recently learned I can't use conditionals in javascript regex. Is there a solution in regular javascript?
Regex code I have so far
/\.[^.]*\.?/
^[^.]*\.(?=[^.]*\.)
Try this.Replace by empty string.See demo.
https://regex101.com/r/sH8aR8/36
var re = /^[^.]*\.(?=[^.]*\.)/;
var str = 'abc.def.ghi\n\n';
var subst = '';
var result = str.replace(re, subst);
Try this:
str = "abc.def.ghi"
newStr = str.replace(/^[^.]*\.(.*?\.)/, '$1') // def.ghi
Demo

Validating Currency on Javascript using a regex not working

I need a regular expression for currency type.
Requirements :
1. First char can be a '$'. It can appear either 0 or 1 times.
2. Then a digit can appear multiple times.
3. Then a decimal point can appear either 0 or 1 time.
4. After this, a digit can appear 0 or more times.
I have written the following regular expression :
\$?\d+\.?\d*
I need to test this on JS . This is how i test this on JS;
var str = "$cng";
var patt = new RegExp('[\$?\d+\.?\d*]');
var res = patt.test(str);
console.log(res);
The above string $cng is returning true. I am not able to get it. Am i missing anything here. Can anyone please help. Thanks in advance.
You must need to escape all the backslashes one more times when passing it to the RegExp constructor which has double quotes as delimiter.
And also i suggest you to remove the square brackets around your pattern.
So change your pattern like below,
var patt = new RegExp("^\\$?\\d+\\.?\\d*$");
OR
var patt = new RegExp("^\\$?\\d+(?:\\.\\d+)?$");
Example:
> var str = "$123.12";
undefined
> var patt = new RegExp("^\\$?\\d+(?:\\.\\d+)?$");
undefined
> patt.test(str);
true
> var patt = new RegExp("^\\$?\\d+(?:\\.\\d+)?$");
undefined
> patt.test('$123.12$');
false
Replace RegExp('[\$?\d+\.?\d*]') with RegExp(/\$?\d+\.?\d*/) and it will work as expected.
Working Code Snippet:
var str = "$100.10";
var patt = new RegExp(/^\$?\d+\.?\d*$/);
var res = patt.test(str);
console.log(res);
EDIT:
You can also simply do: var res = /^\$?\d+\.?\d*$/.test(str);
Your regular expression should also match the beginning and end of the string, otherwise it will only test if the string contains a currency:
^\$?\d+\.?\d*$
You added brackets around the regular expression when you implemented it in Javascript, which changes the meaning entirely. The pattern will find a match if any of the characters within the brackets exist in the string, and as there is a $ in the string the result was true.
Also, when you have a regular expression in a string, you have to escape the backslashes:
var patt = new RegExp('^\\$?\\d+\\.?\\d*$');
You can also use a regular expression literal to create the object:
var patt = /^\$?\d+\.?\d*$/;
You might want to change the requirements so that the decimal point only is allowed if there are digits after it, so that for example $1. is not a valid value:
^\$?\d+(\.\d+)?$
[\$?\d+\.?\d*]==>[] is a character class.
Your regex will just match 1 character out of the all defined inside the character class.
Use
^\\$?\\d+\\.?\\d*$
or
/^\$?\d+\.?\d*$/
to be very safe.

javascript, regex parse string content in curly brackets

i am new to regex. I am trying to parse all contents inside curly brackets in a string. I looked up this post as a reference and did exactly as one of the answers suggest, however the result is unexpected.
Here is what i did
var abc = "test/abcd{string1}test{string2}test" //any string
var regex = /{(.+?)}/
regex.exec(abc) // i got ["{string1}", "string1"]
//where i am expecting ["string1", "string2"]
i think i am missing something, what am i doing wrong?
update
i was able to get it with /g for a global search
var regex = /{(.*?)}/g
abc.match(regex) //gives ["{string1}", "{string2}"]
how can i get the string w/o brackets?
"test/abcd{string1}test{string2}test".match(/[^{}]+(?=\})/g)
produces
["string1", "string2"]
It assumes that every } has a corresponding { before it and {...} sections do not nest. It will also not capture the content of empty {} sections.
var abc = "test/abcd{string1}test{string2}test" //any string
var regex = /{(.+?)}/g
var matches;
while(matches = regex.exec(abc))
console.log(matches);
Try this:
var abc = "test/abcd{string1}test{string2}test" //any string
var regex = /{(.+?)}/g //g flag so the regex is global
abc.match(regex) //find every match
a good place to read about Regex in javascript is here, and a nice place to test is here
good luck!
Nothing wrong. But you'll need to look at your capturing groups (the second element in the array) to get the content you wanted (you can ignore the first). To get all occurences, it's not enough to run exec once, you'll need to loop over the results using match.
Edit: nevermind that, afaik you can't access capturing groups with match. A simpler solution would be using a positive lookahead, as Mike Samuel suggested.
This result:
["{string1}", "string1"]
is showing you that for the first match, the entire regex matched "{string1}" and the first capturing parentheses matched "string1".
If you want to get all matches and see all capturing parens of each match, you can use the "g" flag and loop through, calling exec() multiple times like this:
var abc = "test/abcd{string1}test{string2}test"; //any string
var regex = /{(.+?)}/g;
var match, results = [];
while (match = regex.exec(abc)) {
results.push(match[1]); // save first captured parens sub-match into results array
}
// results == ["string1", "string2"]
You can see it work here: http://jsfiddle.net/jfriend00/sapfm/
try this for file
const fs = require('fs');
fs.readFile('logs.txt', function(err, data) {
if(err) throw err;
const paragraph = "'" + data + "'";
const regex = /\d+\<;>\S+\<;>(\d+)\<;/g;
const found = paragraph.match(regex);
console.log(found);
})

Categories