JavaScript .replace doesn't replace all occurrences [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript multiple replace
How do I replace all occurrences of "/" in a string with "_" in JavaScript?
In JavaScript, "11.111.11".replace(".", "") results in "11111.11". How can that be?
Firebug Screenshot:

Quote from the doc:
To perform a global search and replace, either include the g switch in
the regular expression or if the first parameter is a string, include
g in the flags parameter. Note:
The flags argument does not work in v8 Core (Chrome and Node.js) and will be removed from Firefox.
So it should be:
"11.111.11".replace(/\./g, '');
This version (at the moment of edit) does work in Firefox...
"11.111.11".replace('.', '', 'g');
... but, as noted at the very MDN page, its support will be dropped soon.

With a regular expression and flag g you got the expected result
"11.111.11".replace(/\./g, "")
it's IMPORTANT to use a regular expression because this:
"11.111.11".replace('.', '', 'g'); // dont' use it!!
is not standard

First of all, replace() is a javascript function, and not a jquery function.
The above code replaces only the first occurrence of "." (not every occurrence). To replace every occurrence of a string in JavaScript, you must provide the replace() method a regular expression with a global modifier as the first parameter, like this:
"11.111.11".replace(/\./g,'')

Related

Need help to use regex in match function of javascript [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 5 years ago.
I am using a regex for getting some pattern data and it is working fine but I need to use some part of regex from a variable but I am unable to do that please help me if somebody know how to make it.
var subStr = document_root.documentElement.outerHTML.match(/http(.*?Frover.fff.com.*?)\;/g);
alert(subStr[0]);
I get first result in alert but need to do it like this.
var link=rover.fff.com;
var regexpattern="/http(.*?F"+link+".*?)\;/g"
var rex=new RegExp(regexpattern);
var subStr = document_root.documentElement.outerHTML.match(regexpattern);
alert(subStr[0]);
I don't get anything.
Please help me.
Comment if you confuse in anything.
In JavaScript, when you need to use a variable, you have to create a new RegExp object, as you've tried.
It takes two parameters. The first is a string of the pattern (without the slashes at the start and end). The second is any flags (like your g).
So, your pattern would be something like this:
var regexpattern = new RegExp('http(.*?F' + link + '.*?)\\;', 'g')
Note, that you have to escape any special characters in the string like you would any other string (in this case, your \ had to be escaped to \\ so it'll work properly).
After that, you use it the same as the /pattern/ form. In your case, be sure to use rex, not regexpattern in your match() function.
(If so some reason that wasn't a literal \ and you were escaping the semi-colon, just remove it completely, you won't need to escape a semi-colon.)

Escaping text for regex [duplicate]

This question already has answers here:
Javascript equivalent of Perl's \Q ... \E or quotemeta()
(3 answers)
Closed 2 years ago.
In Perl, there's a function named quotemeta which accepts a string and returns a regex pattern that matches that string. It's used in virtually every program to avoid code injection bugs.
One would use quotemeta when dynamically building a pattern. For example,
"^"+quotemeta(var)+"_\\d+$"
A JavaScript implementation follows:
function quotemeta(s) {
return String(s).replace(/\W/g, "\\$&");
}
Given how needed this function when working with regex patterns, I would have expected JavaScript to provide one. Does JavaScript or jQuery already have such a function?
JavaScript doesn't have such a method natively. (And jQuery doesn't include one)
Usually, when searching for a string pattenr, you'd use String.prototype.indexOf. This method find a string in a string, so you won't even need to convert the string pattern to a regex.
String.prototype.replace can also take a String pattern.
It is not exactly the same but it'll work for most string matching use cases.

String.prototype.replaceAll() not working [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 2 years ago.
I need to replace all the string in a variable.
var a = "::::::";
a = a.replace(":", "hi");
console.log(a);
The above code replaces only the first string i.e..hi::::::
I used replaceAll but it's not working.
Update: All recent versions of major browsers, as well as NodeJS 15+ now support replaceAll
Original:
There is no replaceAll in JavaScript: the error console was probably reporting an error.
Instead, use the /g ("match globally") modifier with a regular expression argument to replace:
const a = "::::::";
const replaced = a.replace(/:/g,"hi");
console.log(replaced);
The is covered in MDN: String.replace (and elsewhere).
There is no replaceAll function in JavaScript.
You can use a regex with a global identifier as shown in pst's answer:
a.replace(/:/g,"hi");
An alternative which some people prefer as it eliminates the need for regular expressions is to use JavaScript's split and join functions like so:
a.split(":").join("hi");
It is worth noting the second approach is however slower.

Preparing a regular expression for javascript

I have made this regular expression which does exactly what I want when I test it in e.g. RegExr:
^https?:\/\/(www\.)?(test\.yahoo\.com|sub\.yahoo\.com)?(?!([a-z0-9]+\.)?(localhost|yahoo\.com))(.*)?
However when I test it in javascript it says that the expression is invalid. After hours of debugging I found out that this expression works in javascript:
^https?:\/\/(www\.)?(test\.yahoo\.com|sub\.yahoo\.com)?(?![a-z0-9]+\.)?(localhost|yahoo\.com)(.*)?
However this doesn't do what I want (again testing in RegExr).
Why cannot I use the first expression in javascript? And how do I fix it?
UPDATE JULY 25
Sorry for the lack of info. The way I am using the Regexp is through a jQuery extension which lets me select using regexp. The script can be seen here: http://james.padolsey.com/javascript/regex-selector-for-jquery/
The specific code I am trying to get to work is:
$('a:regex(href, ^https?:\/\/(www\.)?(test\.yahoo\.com|sub\.yahoo\.com)?(?!([a-z0-9]+\.)?(localhost|yahoo\.com))(.*)?)').live('click', function(e) {
After including the linked jQuery plugin. The text strings I am testing are:
http://yahoo.com
http://google.dk
http://subdomain.yahoo.com
http://test.yahoo.com
http://localhost.dk
http://sub.yahoo.com/lalala
Where it is supposed to match "http://google.dk", "http://test.yahoo.com" and "http://sub.yahoo.com/lalala" - which it does when using RegExr but failing (invalid expression) using the jQuery plugin.
The first regular expression is not invalid:
var regexp = /^https?:\/\/(www\.)?(test\.yahoo\.com|sub\.yahoo\.com)?(?!([a-z0-9]+\.)?(localhost|yahoo\.com))(.*)?/;
works fine.
If you want to instantiate the expression from a string, you have to double all the backslashes:
var regexp = new RegExp("^https?:\\/\\/(www\\.)?(test\\.yahoo\\.com|sub\\.yahoo\\.com)?(?!([a-z0-9]+\\.)?(localhost|yahoo\\.com))(.*)?");
When you start from a string, you have to account for the fact that the string constant itself uses backslashes as a quoting mechanism, so there will be two evaluations made: one as a string, and one as a regular expression.
edit — OK I think I see the problem. That plugin you're trying to use is simply attempting to do something that's just not going to work, given the way that Sizzle parses selectors. In other words, the problem is not with your regular expression, it's with the overall selector. It is not even getting far enough to parse the regular expression.
Specifically it seems to be nested parentheses inside the regular expression. Something as simple as
$('a:regex(href, ((abc)))')
causes an error. You can instead do something like this:
$('a').filter(function() {
return /^https?:\/\/(www\.)?(test\.yahoo\.com|sub\.yahoo\.com)?(?!([a-z0-9]+\.)?(localhost|yahoo\.com))(.*)?/.test(this.href);
}).whatever( ... );

Why does a $ in the replacement string passed to the replace() function break some of the time? [duplicate]

This question already has answers here:
`string.replace` weird behavior when using dollar sign ($) as replacement
(3 answers)
Closed last month.
I have a variable that I'm using to build a JavaScript function call, and JavaScript's .replace() to surround the line of text with a span and onclick event. The .replace() portion looks like this:
code.replace(/(\d{4}\s+)?(LOCAL|PARAMETER|GLOBAL)\s+USING\s+([\S]+)/g,
"<span class=\"natprint_popup\" onclick=\"getNaturalCode('"
+ lib
+ "','$3','##test_prod_qual|',0,'Y'); return false;\">$&</span>");
The only problem is that the variable lib contains a $ at the end some of the time; for example, lib == DPDRI$. This causes the JavaScript on my page to break and I get output that breaks at the end of lib and displays the rest of the Javascript function parameters as plain text:
,'DPDPDRNO','TEST',0,'Y'); return false;">
I've been looking fruitlessly for answers for a few days now. I've tried doing lib.replace(/\$/g, "\\$"); and the \$ is successfully making its way into the variable but it still breaks my code. It seems like the JavaScript engine is trying to interpret the $ at the end of lib as a captured match and it's making it blow up. Anyone have any ideas how to make this work?
See the Specifying a string as a parameter section of the replace() documentation on MDC:
The replacement string can include the following special replacement patterns:
Pattern Inserts
$$ Inserts a "$".
...
$' Inserts the portion of the string that follows the matched substring.
...
Note that since the contents of your variable is being inserted as a single-quote-wrapped parameter to the function you're calling from onclick, it will always be followed by a ' - so when it ends with a $, you'll have inadvertently created a replacement pattern:
... onclick=\"getNaturalCode('DPDRI$' ...
Now, you could just change how you quote that particular parameter. But to be safe, you should really escape the $ symbol:
+ lib.replace(/\$/g, "$$$$")
The above modification will convert "DPDRI$" into "DPDRI$$" prior to its insertion into the replacement string, allowing the final replacement to contain a literal $.

Categories

Resources