javascript regex match works but replace doesnt work - javascript

I am trying to use regex replace with a regex I have. When I use the match method it returns the array with the proper index and match but when I use replace and add the replace string it wouldnt work.
var a = "$#,##0.00".match("[\\d+-,#;()\\.]+");
console.log(a);
Returns ["#,##0.00", index: 1, input: "$#,##0.00"].
var b = "$#,##0.00".replace("[\\d+-,#;()\\.]+","");
console.log(b);
Returns $#,##0.00 whereas I expect it to return just the $
Can someone point out what am I doing incorrectly? Thanks
Link to the example is:
var a = "$#,##0.00".match("[\\d+-,#;()\\.]+");
console.log(a);
var b = "$#,##0.00".replace("[\\d+-,#;()\\.]+","");
console.log(b);

.match only accepts regexps. So if a string is provided .match will explicitly convert it to a regexp using new RegExp.
.replace however accepts both a string (which will be taken literally as the search) or a regexp, you have to pass in a regexp if you want it to use a regexp.
var b = "$#,##0.00".replace(new RegExp("[\\d+-,#;()\\.]+"), "");
// ^^^^^^^^^^^ ^
or using a regexp literal:
var b = "$#,##0.00".replace(/[\d+-,#;()\.]+/, "");

Related

How to get next 3 characters after a substring if it exist inside a string?

I have this string that's. The &# substring is common but number after it changes in almost every object of my JSON data. So I want to detect if there is this substring, then get next three characters after it replace it with something else. How can I do it?
You can do it like this
var para = 'that's';
para = para.substr(para.indexOf('#')+1, 3);
syntax:
substr(start, length)
indexOf(searchvalue, [start])
Assuming you want to replace everything from &# until ; (if not, please update your question by specifying expected output):
You can use String.prototype.replace() with a regular expression:
var para = 'some string ' middle † end';
para = para.replace(/&#([\d]*);/g, 'replacement');
The g modifier is important to replace all occurences in the string.
With the RegEx used, you can include the found number (between &# and ;) in the replacement string by using $1.
you can define and use a utility function to replace HTML entities like that:
function decode(text, replaceWith = '') {
return text.replace(/&#(\d+);/g, replaceWith)
}

remove last part of string following '&&&' with JavaScript Regex

I'm trying to use a regex in JS to remove the last part of a string. This substring starts with &&&, is followed by something not &&&, and ends with .pdf.
So, for example, the final regex should take a string like:
parent&&&child&&&grandchild.pdf
and match
parent&&&child
I'm not that great with regex's, so my best effort has been something like:
.*?(?:&&&.*\.pdf)
Which matches the whole string. Can anyone help me out?
You may use this greedy regex either in replace or in match:
var s = 'parent&&&child&&&grandchild.pdf';
// using replace
var r = s.replace(/(.*)&&&.*\.pdf$/, '$1');
console.log(r);
//=> parent&&&child
// using match
var m = s.match(/(.*)&&&.*\.pdf$/)
if (m) {
console.log(m[1]);
//=> parent&&&child
}
By using greedy pattern .* before &&& we make sure to match **last instance of &&& in input.
You want to remove the last portion, so replace it
var str = "parent&&&child&&&grandchild.pdf"
var result = str.replace(/&&&[^&]+\.pdf$/, '')
console.log(result)

What is the difference between RegExp("str","i") and '/'+"str"+'/i'

I tried to do a case insensitive regular expression search by creating a string like so:
var regEx = '/'+myStr+'/i';
but when I use it in a search, it always returns -1.
If I use:
var regEx = RegExp(myStr,'i');
it works like a champ.
I'd just like to understand why?
You first example will create a string, not a regular expression object.
var myStr = 'test';
var regEx = '/'+myStr+'/i';
console.log(typeof regEx);//string
Using RegExp will create a regular expression object.
var myStr = 'test';
var regEx = RegExp(myStr,'i');
console.log(typeof regEx);//object
Thus when you try to use the search method, you are searching with a string on slashes on both sides, thus getting -1.
var s = 'just a test string';
console.log(s.search('/test/'));//-1
console.log(s.search(/test/));//7
Of course, the string search method can work with a string, in which case it will search for that specific substring, which in your case does not exist, so it returns the -1 index. In your example slashes were being added to the string, rather than producing the intended regular expression.
In JavaScript, there are two ways of creating a regular expression object (short of using code evaluation), a regular expression literal, and one created by the RegExp constructor.
A regular expression literal has to be defined at compile time, and cannot be constructed from string concatenation.
/test/i
To dynamically create a regular expression at runtime, you have to use the RegExp constructor.
RegExp('test', 'i');

Matching a string with a regex gives null even though it should match

I am trying to get my regex to work in JavaScript, but I have a problem.
Code:
var reg = new RegExp('978\d{10}');
var isbn = '9788740013498';
var res = isbn.match(reg);
console.log(res);
However, res is always null in the console.
This is quite interesting, as the regex should work.
My question: then, what is the right syntax to match a string and a regex?
(If it matters and could have any say in the environment: this code is taken from an app.get view made in Express.js in my Node.js application)
Because you're using a string to build your regex, you need to escape the \. It's currently working to escape the d, which doesn't need escaping.
You can see what happens if you create your regex on the chrome console:
new RegExp('978\d{10}');
// => /978d{10}/
Note that there is no \d, only a d, so your regex matches 978dddddddddd. That is, the literal 'd' character repeated 10 times.
You need to use \\ to insert a literal \ in the string you're building the regex from:
var reg = new RegExp('978\\d{10}');
var isbn = '9788740013498';
var res = isbn.match(reg);
console.log(res)
// => ["9788740013498", index: 0, input: "9788740013498"]
You need to escape with double back slash if you use RegExp constructor:
var reg = new RegExp('978\\d{10}');
Quote from documentation:
When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:
var re = /\w+/;
var re = new RegExp("\\w+");

Extracting a substring with a JavaScript regular expression;

Consider this code:
var myregexp = "\\*(.+)"; // set from another subsystem, that's why I'm not using a literal regexp
var input = "Paypal *Steam Games";
var output = input.match(new RegExp(myregexp, 'gi'), "$1");
The output is ["*Steam Games"], but I would like it to be just ["Steam Games"].
What is wrong?
PS A great resource I found today: http://regex101.com/#javascript
match doesn’t accept a second argument.
Since you have the global flag set (and I assume it’s intentional), you’ll need exec to find all of the first groups:
var m;
while ((m = re.exec(input)) {
alert(m[1]); // Get group 1
}
var str = "Paypal *Steam Games";
var reg = /\w+\s?\*(\w+\s?\w+)/; // or your exp will work too `/\*(.+)/;`
console.log(reg.exec(str)[1]); // result Steam Games
JSFiddle
You'll get Steam Games from your string with help of /\w+\s?\*(\w+\s?\w+)/ exp
In JavaScript there are three main RegExp functions:
exec A RegExp method that executes a search for a match in a
string. It returns an array of information.
match A String method that executes a search for a match in a
string. It returns an array of information or null on a mismatch.
test A RegExp method that tests for a match in a string. It
returns true or false.

Categories

Resources