Regex not working with JavaScript str.replace - javascript

I have the below code in php
<?php
$html = "\\x3Cstyle\\x3E\\x0A\\x20\\x20\\x20.mainDiv";
$html = preg_replace_callback(
"/\\\\x([0-9A-F]{1,2})/i",
function ($m) {
return chr(hexdec($m[1]));
},
$html
);
echo $html;
?>
Output :
<style>
.mainDiv
I want to achive the same thing with JS, but I don't think, my regex is working with js
var str = "\\x3Cstyle\\x3E\\x0A\\x20\\x20\\x20.mainDiv";
var newString = str.replace(/\\\\x([0-9A-F]{1,2})/i, function (i){
console.log(i); // just want to see what comes here, later I will convert hex to dec to char
return i;
});
console.log(newString);

You can use
var str = "\\x3Cstyle\\x3E\\x0A\\x20\\x20\\x20.mainDiv";
var newString = str.replace(/\\x([0-9a-f]{2})/gi, function (m,g){
return String.fromCharCode(parseInt(g, 16));
});
console.log(newString);
In the regex literal notation in JavaScript, /.../, a backslash does not form any string escape sequences, it is treated as a literal char. Hence, to match a literal \ char, one needs to use only two backslashes.
In JavaScript, String#replace replaces either the first occurrence (if there is no g flag) or all occurrences (if g flag is provided). Since you used preg_replace in PHP, you need to provide g flag since this is the default preg_replace behavior.
Also, note that you need to pass two arguments in the anonymous callback function since you only need the captured part to convert to a char. m is the whole match value and g is the Group 1 value.

I think what you 're looking for is this:
var str = "\\x3Cstyle\\x3E\\x0A\\x20\\x20\\x20.mainDiv";
var newString = str.replace(/\\x([0-9A-F]{1,2})/gi, function (i){
i = '!MATCHED!'
return i;
});
console.log(newString);
g modifier: global. All matches (don't return on first match)
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
Don't think you need to escape backslashes here

Related

Finding ++ in Regular Expression

I want to find ++ or -- or // or ** sign in in string can anyone help me?
var str = document.getElementById('screen').innerHTML;
var res = str.substring(0, str.length);
var patt1 = ++,--,//,**;
var result = str.match(patt1);
if (result)
{
alert("you cant do this :l");
document.getElementById('screen').innerHTML='';
}
This finds doubles of the characters by a backreference:
/([+\/*-])\1/g
[from q. comments]: i know this but when i type var patt1 = /[++]/i; code find + and ++
[++] means one arbitrary of the characters. Normally + is the qantifier "1 or more" and needs to be escaped by a leading backslash when it should be a literal, except in brackets where it does not have any special meaning.
Characters that do need to be escaped in character classes are e.g. the escape character itself (backslash), the expression delimimiter (slash), the closing bracket and the range operator (dash/minus), the latter except at the end of the character class as in my code example.
A character class [] matches one character. A quantifier, e.g. [abc]{2} would match "aa", "bb", but "ab" as well.
You can use a backreference to a match in parentheses:
/(abc)\1
Here the \1 refers to the first parentheses (abc). The entire expression would match "abcabc".
To clarify again: We could use a quantifier on the backreference:
/([+\/*-])\1{9}/g
This matches exactly 10 equal characters out of the class, the subpattern itself and 9 backreferences more.
/.../g finds all occurrences due to the modifier global (g).
test-case on regextester.com
Define your pattern like this:
var patt1 = /\+\+|--|\/\/|\*\*/;
Now it should do what you want.
More info about regular expressions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
You can use:
/\+\+|--|\/\/|\*\*/
as your expression.
Here I have escaped the special characters by using a backslash before each (\).
I've also used .test(str) on the regular expression as all you need is a boolean (true/false) result.
See working example below:
var str = document.getElementById('screen').innerHTML;
var res = str.substring(0, str.length);
var patt1 = /\+\+|--|\/\/|\*\*/;
var result = patt1.test(res);
if (result) {
alert("you cant do this :l");
document.getElementById('screen').innerHTML = '';
}
<div id="screen">
This is some++ text
</div>
Try this:-
As
n+:- Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
We need to use backslash before this special characters.
var str = document.getElementById('screen').innerHTML;
var res = str.substring(0, str.length);
var patt1 = /\+\+|--|\/\/|\*\*/;
var result = str.match(patt1);
if (result)
{
alert("you cant do this :l");
document.getElementById('screen').innerHTML='';
}
<div id="screen">2121++</div>

Regex split comma except escaped [duplicate]

I have this string:
a\,bcde,fgh,ijk\,lmno,pqrst\,uv
I need a JavaScript function that will split the string by every , but only those that don't have a \ before them
How can this be done?
Here's the shortest thing I could come up with:
'a\\,bcde,fgh,ijk\\,lmno,pqrst\\,uv'.replace(/([^\\]),/g, '$1\u000B').split('\u000B')
The idea behind is to find every place where comma isn't prefixed with a backslash, replace those with string that is uncommon to come up in your strings and then split by that uncommon string.
Note that backslashes before commas have to be escaped using another backslash. Otherwise, javascript treats form \, as escaped comma and produce simply a comma out of it! In other words if you won't escape the backslash, javascript sees this: a\,bcde,fgh,ijk\,lmno,pqrst\,uv as this a,bcde,fgh,ijk,lmno,pqrst,uv.
Since regular expressions in JavaScript does not support lookbehinds, I'm not going to cook up a giant hack to mimic this behavior. Instead, you can just split() on all commas (,) and then glue back the pieces that shouldn't have been split in the first place.
Quick 'n' dirty demo:
var str = 'a\\,bcde,fgh,ijk\\,lmno,pqrst\\,uv'.split(','), // Split on all commas
out = []; // Output
for (var i = 0, j = str.length - 1; i < j; i++) { // Iterate all but last (last can never be glued to non-existing next)
var curr = str[i]; // This piece
if (curr.charAt(curr.length - 1) == '\\') { // If ends with \ ...
curr += ',' + str[++i]; // ... glue with next and skip next (increment i)
}
out.push(curr); // Add to output
}
Another ugly hack around the lack of look-behinds:
function rev(s) {
return s.split('').reverse().join('');
}
var s = 'a\\,bcde,fgh,ijk\\,lmno,pqrst\\,uv';
// Enter bizarro world...
var r = rev(s);
// Split with a look-ahead
var rparts = r.split(/,(?!\\)/);
// And put it back together with double reversing.
var sparts = [ ];
while(rparts.length)
sparts.push(rev(rparts.pop()));
for(var i = 0; i < sparts.length; ++i)
$('#out').append('<pre>' + sparts[i] + '</pre>');
Demo: http://jsfiddle.net/ambiguous/QbBfw/1/
I don't think I'd do this in real life but it works even if it does make me feel dirty. Consider this a curiosity rather than something you should really use.
In case if need remove backslashes also:
var test='a\\.b.c';
var result = test.replace(/\\?\./g, function (t) { return t == '.' ? '\u000B' : '.'; }).split('\u000B');
//result: ["a.b", "c"]
In 2022 most of browsers support lookbehinds:
https://caniuse.com/js-regexp-lookbehind
Safari should be your only concern.
With a lookbehind you can split your string this way:
"a\\,bcde,fgh,ijk\\,lmno,pqrst\\,uv".split(/(?<!\\),/)
// => ['a\\,bcde', 'fgh', 'ijk\\,lmno', 'pqrst\\,uv']
You can use regex to do the split.
Here is the link to regex in javascript http://www.w3schools.com/jsref/jsref_obj_regexp.asp
Here is the link to other post where the author have used regex for split Javascript won't split using regex
From the first link if you note you can create a regular expression using
?!n Matches any string that is not followed by a specific string n
[,]!\\

Add variable into string

All I need to do here is to add a variable before each specific string.
Example:
var exampleString = "blabla:test abcde 123test:123";
var formattedString = "el.blabla:test abcde el.123test:123";
As you can see, when I have something like "XXX:XXX", I need to add a variable before it.
I have the Regex to find "XXX:"
var regex = new RegExp(/\w+([aA-zZ]:)/g)
But when I try to replace it, it replaces all instead of adding the variable "el."
var exampleString = "blabla:test abcde 123test:123";
var formattedString = exampleString.replace(new RegExp(/\w+([aA-zZ]:)/g), 'el.');
// formattedString is now "el.test abcde el.123"
// Instead of "el.blabla:test abcde el.123test:123"
Could anyone makes this work ? Thanks :)
Source: Javascript Regex: How to put a variable inside a regular expression?
var exampleString = "blabla:test abcde 123test:123";
var formattedString = exampleString.replace(/\w*:\w*/gi, 'el.$&');
console.log(formattedString);
Regex use and Explanation Here https://regex101.com/r/U2KeXi/3
Sample Fiddle here https://jsfiddle.net/a8wyLb0g/2/
You need to use ^ to match only at the beginning. And remove the g modifier, since you only want to replace once, not every time.
There's also no reason to use new RegExp(), just use a RegExp literal.
In the replacement string, you need to use $& to copy the original string into the replacement.
var exampleString = "blabla:test abcde 123test:123";
var formattedString = exampleString.replace(/^\w+[a-z]:/i, 'el.$&');
console.log(formattedString);
Also, the proper way to match all letters in either case is with [A-Za-z], not [aA-zZ], or use the i modifier to make the regexp case-insensitive. Your regexp matches all characters in the range A-z, which includes lots of punctuation characters that are between the uppercase letters and lowercase letters in the ASCII code.
Just use this
exampleString.replace(/(\w*):(\w*)/gi, 'el.$1:$2');
REGEXP explanation :
capturing group (\w*) is for capturing any alphabets in any number of occurance,
$1 and $2 specifies the first and second capturing group.
You should use a function like insertAt instead replace, see following example:
String.prototype.insertAt=function(index, string) {
return this.substr(0, index) + string + this.substr(index);
}
var exampleString = "blabla:test abcde 123test:123";
var regex = new RegExp(/\w+([aA-zZ]:)/g)
var formattedString = exampleString;
while ( (result = regex.exec(exampleString)) ) {
formattedString = formattedString.insertAt(result.index, "el.");
}
console.log(formattedString);
I hope it helps you, bye.

how to config RegExp when string contains parentheses

I'm sure this is an easy one, but I can't find it on the net.
This code:
var new_html = "foo and bar(arg)";
var bad_string = "bar(arg)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
sets bad_start to -1 (not found). If I remove the (arg), it runs as expected (bad_start == 8). Is there something I can do to make the (very handy) "new Regexp" syntax work, or do I have to find another way? This example is trivial, but in the real app it would be doing global search and replace, so I need the regex and the "g". Or do I?
TIA
Escape the brackets by double back slashes \\. Try this.
var new_html = "foo and bar(arg)";
var bad_string = "bar\\(arg\\)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
Demo
Your RegEx definition string should be:
var bad_string = "bar\\(arg\\)";
Special characters need to be escaped when using RegEx, and because you are building the RegEx in a string you need to escape your escape character :P
http://www.regular-expressions.info/characters.html
You need to escape the special characters contained in string you are creating your Regex from. For example, define this function:
function escapeRegex(string) {
return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
}
And use it to assign the result to your bad_string variable:
let bad_string = "bar(arg)"
bad_string = escapeRegex(bad_string)
// You can now use the string to create the Regex :v:

JavaScript Regular Expression with character class quantifier variable [duplicate]

This question already has answers here:
JavaScript regex pattern concatenate with variable
(3 answers)
Closed 4 years ago.
I am trying to create a regular expression with a character class that has a specific quantifier which is a variable for example:
var str = "1234.00";
var quantifier = 3;
str = str.replace(/(\d)(\d{quantifier}\.)/,"$1,$2");
//str should be "1,234.00"
This works as follows (without a variable):
var str = "1234.00";
str = str.replace(/(\d)(\d{3}\.)/,"$1,$2");
//str == "1,234.00"
However it does not have the same functionality with a quoted pattern instead of a slash-delimited pattern as follows:
var str = "1234.00";
str = str.replace("(\d)(\d{3}\.)","$1,$2");
//str == "1234.00" - not "1,234.00"
//quote symbol choice does not change this
str = str.replace('(\d)(\d{3}\.)',"$1,$2");
//str == "1234.00" - not "1,234.00"
edit: to be more clear I have added a summary question which was answered below:
How do I create a regular expression with an interpolated variable from a quoted string?
Although my preference would be to use interpolation, it seems that is not available (at least in this context), and is not necessary.
I have also tried to come up with a way to concatenate/join some regex literals to achieve the same result, but have been unable to do so for this use case.
As a side note - I am familiar with this type of regular expression in perl:
my $str = "1234.00";
my $quantifier = 3;
$str =~ s/(\d)(\d{$quantifier}\.)/$1,$2/;
# $str eq "1,234.00"
Which can be made useful as follows:
my $str = "1234567890.00";
for my $quantifier (qw(9 6 3)) {
$str =~ s/(\d)(\d{$quantifier}\.)/$1,$2/;
}
# $str eq "1,234,567,890.00"
With the suggestions/answers provided I have created a sample currency string prototype as follows:
String.prototype.toCurrency = function() {
var copy = parseFloat(this).toFixed(2);
for (var times = parseInt(copy.length/3); times > 0; times--) {
var digits = times * 3;
var re = new RegExp("(\\d)(\\d{" + digits + "}\\.)");
copy = copy.replace(re,"$1,$2");
}
return '$'+copy;
};
str = "1234567890";
str.toCurrency();
// returns "$1,234,567,890.00"
There are two problems with this statement:
str.replace("(\d)(\d{3}\.)","$1,$2");
The first is that you are passing a string and not a regular expression object, and the second is that within a string literal the backslash has a special meaning to escape certain things (e.g., "\n" is a newline) so to have an actual backslash in your string literal you need to double it as "\\". Using the RegExp() constructor to create a regex object from a string you get this:
str.replace(new RegExp("(\\d)(\\d{3}\\.)"),"$1,$2");
So from there you can do this:
var quantifier = 3
str = str.replace(new RegExp("(\\d)(\\d{" + quantifier + "}\\.)"),"$1,$2");
In JavaScript, you can't concatenate or interpolate into regex literals, but you can create a regex from a string by using the RegExp constructor:
str = str.replace(new RegExp('(\\d)(\\d{' + quantifier + '}\\.'), "$1,$2");
Note, by the way, that this:
str.replace(..., ...);
has no effect, because replace doesn't modify a string, but rather, it returns a copy of the string with the replacements made. So you need to write this:
str = str.replace(..., ...);
instead.
You can create a RegExp object:
var str = "1234.00";
var digits = 2;
var re = new RegExp("(\\d)(\\d{" + digits + "})");
var str2 = str.replace(re,"$1,$2-");
str2 would contain 1,23-4.00.
Working example:
http://jsfiddle.net/JuZtc/
Note that you need to escape \ in strings, thus \\.
Hope this helps.

Categories

Resources