Javascript RegExp find and replace empty square brackets - javascript

I have a string that contains something like name="text_field_1[]" and I need to find and replace the '1[]' part so that I can increment like this '2[]', '3[]', etc.
Code:
$search = new RegExp('1[]', 'g');
$replace = $number + '[]';
$html = $html.replace($search, $replace)

You can use \d in your regexp whitch means that onlu numbers used before [].
Also you need to escape [] because of it's special characters in regexp.
$search = new RegExp('\\d+\\[\\]', 'g');
$replace = $number + '[]';
$html = $html.replace($search, $replace)
Code: http://jsfiddle.net/VJYkc/1/

You can use callbacks.
var $counter = 0;
$html = $html.replace(/1\[\]/g, function(){
++$counter;
return $counter+'[]';
});
If you need [] preceded by any number, you can use \d:
var $counter = 0;
$html = $html.replace(/\d\[\]/g, function(){
++$counter;
return $counter+'[]';
});
Note:
escape brackets, because they are special in regex.
be sure that in $html there is only the pattern you need to replace, or it will replace all 1[].

Braces must be escaped within regexps...
var yourString="text-field_1[]";
var match=yourString.match(/(\d+)\[\]/);
yourString=yourString.replace(match[0], parseInt(match[1]++)+"[]");

Here's something fun. You can pass a function into string.replace.
var re = /(\d+)(\[\])/g/;
html = html.replace(re, function(fullMatch, value, braces) {
return (parseInt(value, 10)+1) + braces;
}
Now you can replace multiple instances of #[] in your string.

Related

Regex not working with JavaScript str.replace

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

how to use split() function with html tag and whitespace

I use split(" ") for whitespace and use split(/(<[^>]*>)/) for html tag in string.
but i have to use together. i want to divide a string by whitespace and html tag and put it into an array. i don't want to lose anything. string, html tag both.
whitespace is \s and html tag is split(/(<[^>]*>)/) and i used like this new RegExp("\s+(<[^>]*>)", "g");
but it doesn't work.
var htmlTagRegex = new RegExp("\s+(<[^>]*>)", "g");
var str = ""<div class="tab0">CSS code formatter</div><div class="tab2">CSS code compressor</div>";
var myArray = str.split(htmlTagRegex);
if(myArray != null){
for ( i = 0; i < myArray.length; i++ ) {
var result = "myArray[" + i + "] = " + myArray[i]+"<br />";
$(".tt-sns-clear").append(result);
}
}
Not 100% sure what you are trying to do but it looks like the space needs to be optional like \s* instead of \s+
Something like : \s*(<[^>]*>)
And since you are not concatenating a string to your Regex better is:
var htmlTagRegex =/\s*(<[^>]*>)/g
The input string is not using double quotes correctly and it is not compiling either, you need to mix single and double quotes:
'<div class="tab0">CSS code formatter</div><div class="tab2">CSS code compressor</div>';
All together looks like
var htmlTagRegex =/\s*(<[^>]*>)/g
var str = '<div class="tab0">CSS code formatter</div><div class="tab2">CSS code compressor</div>';
var myArray = str.split(htmlTagRegex);
//outputs ["", "<div class="tab0">", "CSS code formatter", "</div>", "", "<div class="tab2">", "CSS code compressor", "</div>", ""]
And it seems to work fine on my end.
string is from mysql. And that is inclueded html tag.
And I used like this: var htmlTagRegex =/\s|(<[^>]*>)/g;
but result is not what i want.
["","CSS","code","formatter","<div class="tab0"></div>","","CSS","code","compressor","<div class="tab1"></div>"]
I want like this
["<div class="tab0">","CSS","code","formatter","","<div class="tab1">","CSS","code","compressor","</div>"]

how to remove particular repeated string from large string

I have one string, I want to remove some repeated part from string using ajax or javascritp.
The string is -
1-16-15-master=1232_2-34-33-master=1232_3-33-23-master=1236
Above string is connect using underscore (_) sign. means above string include 3 string. I want to remove -master=122....
The '-master=' is default but after equal sign(=) number will change. So how to remove '-master=n...' from above string.
var s = "1-16-15-master=1232_2-34-33-master=1232_3-33-23-master=1236";
console.log(s.replace(/-master=\d+/g, ''));
Use a replace function with a greedy /-master=\d+/ regex :
PHP
$input = "1-16-15-master=1232_2-34-33-master=1232_3-33-23-master=1236";
$output = preg_replace('/-master=\d+/', '', $input);
echo $output; // 1-16-15_2-34-33_3-33-23
JS
var input = "1-16-15-master=1232_2-34-33-master=1232_3-33-23-master=1236";
var output = input.replace(/-master=\d+/g, '');
console.log(output); // 1-16-15_2-34-33_3-33-23
Try this:
var str = "1-16-15-master=1232_2-34-33-master=1232_3-33-23-master=1236";
str = str.replace(/-master=/g,'=');

RexExp Passing variable

I have a problem with passing variables into a regExp.
Here my code:
project.highlight = function($st,$search) {
re = new RegExp("/\b("+ $search +")\b/g");
return $st.replace(/\b(lorem)\b/g, '<span class="highlight">$1</span>'); // working
return $st.replace(re, '<span class="highlight">$1</span>'); // not working...
}
What am I doing wrong?
re = new RegExp("\\b("+ $search +")\\b", "g");
With this syntax you must remove delimiters and put the modifier at the end in a separate string. (and use double slashes)

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