Escaping text for regex [duplicate] - javascript

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.

Related

javascript string replace function [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 6 years ago.
I'm using the <string>.replace(/x/g,"y") to replace all instances of a character in a string to a different character, and I get exactly what I need.
My problem is with the syntax of the pattern (i.e. /x/g) that causes issues in a small post-processor I developed for all the javascript files included in my project.
The solution to my problem can be to encapsulate the string replacement within an isolated file that would not undergo post-processing.
(What post-processing does and why I use it is not important here)
My question: Suppose I create a function Switch_All_Chars(In_Str,Old_C,New_C) that replaces all instances of Old_C by New_C in In_str returning the updated string, and it would loo like:
function Switch_All_Chars(In_Str,Old_C,New_C) {
pat = /Old_C/g ;
return In_Str.replace( pat , New_C) ;
}
This would not work because par is not properly defined. Is there a syntax that would allow the definition of the pattern using a variable?
Thanks.
Use RegExp constructor:
var pat = new RegExp(Old_C, "g")

Javascript equivalent to Ruby's single quotes? [duplicate]

This question already has answers here:
Does JavaScript have literal strings?
(6 answers)
Closed 7 years ago.
In Ruby, if you use single quotes to make a string, the program parses it so that the output is literally what you wrote.
For example, if you create a string the following way:
variable_a = 'my\nname\nis\nOliver\nQueen'
the output of puts variable_a is
>>my\nname\nis\nOliver\nQueen
However, if you instead use double quotes when building the string, like so:
variable_b = "my\nname\nis\nOliver\nQueen"
the output of puts variable_b would be
>>my
>>name
>>is
>>Oliver
>>Queen
I am looking for a way in Javascript that does just what the single quotes do in Ruby, so that there will be less mistakes when trying to properly build a string that contains backslashes, and other characters that would 'break' the intended string.
Single and double quotes in Javascript are equivalent. The only real reason to use one over the other is preference, and avoiding escaping embedded quotes, e.g.
"Don't need to escape this apostrophe."
or
'No need to escape this "quoted" word.'
Unless you are talking about JSON. In JSON you must use double quotes or it is considered a syntax error by many parsers.

Is using var foo = new RegExp necessary? [duplicate]

This question already has answers here:
Are /regex/ Literals always RegExp Objects?
(3 answers)
Closed 10 years ago.
While researching the use of regular expressions in javascript, one can encounter examples of two types:
A:
var regex = /^[a-zA-Z0-9]+$/;
B:
var regex = new RegExp ("^[a-zA-Z0-9]*$");
Is it necessary to use var foo = new RegExp? Or, when should one pick each method?
The RegExp() constructor is useful when you have to assemble a regular expression dynamically at run time. If the expression is completely static, it's easier to use the native regex syntax (your "A"). The ease-of-use of the native syntax stems from the fact that you don't have to worry about quoting backslashes, as you do when your regular expression begins life as a string constant.
Is it necessary to use var foo = new RegExp?
No, obviously not. The other one works as well.
Or, when should one pick each method?
Regex literals are easier to read and write as you do not need to string-escape regex escape characters - you can just use them (backslashes, quotes). Also, they are parsed only once during script "compilation" - nothing needs to be executed each time you the line is evaluated.
The RegExp constructor only needs to be used if you want to build regexes dynamically.
Here's an example of a 'dynamic' regular expression where you might need new RegExp.
var search = 'dog',
re = new RegExp('.*' + search + '.*');
If it's a static regular expression, then the literal syntax (your A option) is better because it's easier to write and read.

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.

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

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,'')

Categories

Resources