how to remove just one character in a string of javascript - javascript

#a:{width:100px;height:100px;background-color:black;}#b:{width:100px;}
i have the above string
i want that the character: only after css selector like #a and #b get removed from this string
i thought that i must use regular expressions so i wrote one:
/[#\.A-Za-z0-9]+([:])[{]/g
see this regular expression working on regex101
but you know it matches : but when i try to remove this using replace method then whole #a:{ and #b:{ get removed
any help would be great!

The regex is almost correct. What you need to do is to repalce the with $1$2 instead of null string
Also make a small change to the regex as
/([#.A-Za-z0-9]+):({)/g
Regex Example
Changes made
([#.A-Za-z0-9]+) enclosed in brackets. The matched string is captured in $1 hence for the frist match $1 will contain #a
Within a character class its not required to escape the . as it looses it meaning in the class.
[{] to ({) The [] surrounding does not make any difference, hence drop it. Enclosed in (), hence captured in $2, for example in first match the $2 will contian {
Replace string $1$2
will give output as
#a{width:100px;height:100px;background-color:black;} #b{width:100px;}

Javascript
var value = "#a:{width:100px;height:100px;background-color:black;}#b:{width:100px;}";
alert(value.replace(/(#.):/g, "$1"));
Example: http://jsfiddle.net/7hs0jgd2/

Related

Remove all whitespace EXCEPT what is contained in the capture group

Regex Dialect: JavaScript
I have the following capture group (('|").*?[^\\\2]\2) that selects a quoted string excluding escaped quotes.
Matches these for example...
"Felix's pet"
'Felix\'s pet'
However I would now like to remove all whitespace from a string except anything matching this pattern. Is there perhaps a way to back reference the capture group \1 and then exclude it from the matches?
I have attempted to do so with my limited RegEx knowledge, but so far it I can only select the space immediately preceding or following the pattern.
I have saved my test script on regexr for convenience if you would like to play around with my example.
Intended results:
key : string becomes key:string
dragon : "Felix's pet" becomes dragon:"Felix's pet"
"Hello World" something here "Another String"
becomes
"Hello World"somethinghere"Another String"
etc...
This is extremely hard to do with regular expressions. The following works:
result = subject.replace(/ (?=(?:(?:\\.|"(?:\\.|[^"\\])*"|[^\\'"])*'(?:\\.|"(?:\\.|[^"'\\])*"|[^\\'])*')*(?:\\.|"(?:\\.|[^"\\])*"|[^\\'])*$)(?=(?:(?:\\.|'(?:\\.|[^'\\])*'|[^\\'"])*"(?:\\.|'(?:\\.|[^'"\\])*'|[^\\"])*")*(?:\\.|'(?:\\.|[^'\\])*'|[^\\"])*$)/g, "");
I've built this answer from one of my earlier answers to a similar, but not identical question; therefore I'll refer you to it for an explanation.
You can test it live on regex101.com.
In Javascript, you can use String.replace with function as parameter. So you define matching groups and then you can replace each of them separately.
You want match all white spaces
\s+
and you need match all inside quotes
(('|")(?:[^\\]\\\2|.)*?\2)
so you combine it together
var pattern = /\s+|(('|")(?:[^\\]\\\2|.)*?\2)/g
and you write replace statement with anonymous function as parameter:
var filteredString = notFilteredString.replace(pattern,
function(match, group1) { return group1 || "" })
With each match the function is called to give replace string. The regexp match either white space or content of quote. The content of quote is wrapped as group1 and the anonymous function returns group1 if group1 is matched or nothing "" for white spaces or any other match.

How do I ignore $1 replace backreferencing in javascript

I have a string that a user can edit at any time, and a regex that is being conducted on the string, to add it to an xml and then save it but they can add '$1' to the string. I just want the text '$1' to be saved but I have to perform a regular expression on the same string that $1 is in. It replaces the $1 with a character from the regex every time.
How do I find, and replace, the $1 in this string?
Example of what is happening:
string1 = '<item id="1">i have $100</item>'
regexp = new RegExp('<item id="1"([^<]|<[^\/]|<\/[^i]|<\/i[^t]|<\/it[^e]|<\/ite[^m]|<\/item[^>])*<\/item>');
data = '<data><item id="1">i have no money</item><item id="2">i have no money</item></data>'
data = data.replace(regexp, string1);
Results
<data><item id="1">i have >00</item><item id="2">i have no money</item></data>
If you have a variable string that you want to put in your replace() call which might possibly have $N's in it, you can prevent the $N from being treated as a backreference by replacing $ with $$. Apparently, unlike other special characters in JS regex, the $ character cannot be escaped with a \ - it must be escaped with a preceding $ (go figure).
In your example, you could do the following to fix the issue:
data = data.replace(regexp, string1.replace('$', '$$$'));
This should turn any $'s into $$ in string1, preventing them from being treated as backreferences.
(Note: I found this little nugget here)
This should only happen if you have a capturing group in the regex.
If you don't want your groups to capture, then place ?: inside the start of the group.
/foo(?:bar)/
You can escape the $. Eg:
var replacement = '<item id="1">i have \\$100</item>';
Useful when you have capturing groups and need to write a $.

Nice way to do this regex substitution

I'm writing a javascript function which takes a regex and some elements against which it matches the regex against the name attribute.
Let's say i'm passed this regex
/cmw_step_attributes\]\[\d*\]/
and a string that is structured like this
"foo[bar][]chicken[123][cmw_step_attributes][456][name]"
where all the numbers could vary, or be missing. I want to match the regex against the string in order to swap out the 456 for another number (which will vary), eg 789. So, i want to end up with
"foo[bar][]chicken[123][cmw_step_attributes][789][name]"
The regex will match the string, but i can't swap out the whole regex for 789 as that will wipe out the "[cmw_step_attributes][" bit. There must be a clean and simple way to do this but i can't get my head round it. Any ideas?
thanks, max
Capture the first part and put it back into the string.
.replace(/(cmw_step_attributes\]\[)\d*/, '$1789');
// note I removed the closing ] from the end - quantifiers are greedy so all numbers are selected
// alternatively:
.replace(/cmw_step_attributes\]\[\d*\]/, 'cmw_step_attributes][789]')
Either literally rewrite part that must remain the same in replacement string, or place it inside capturing brackets and reference it in replace.
See answer on: Regular Expression to match outer brackets.
Regular expressions are the wrong tool for the job because you are dealing with nested structures, i.e. recursion.
Have you tried:
var str = 'foo[bar][]chicken[123][cmw_step_attributes][456][name]';
str.replace(/cmw_step_attributes\]\[\d*?\]/gi, 'cmw_step_attributes][XXX]');

JavaScript regex replace - but only part of matched string?

I have the following replace function
myString.replace(/\s\w(?=\s)/,"$1\xA0");
The aim is to take single-letter words (e.g. prepositions) and add a non-breaking space after them, instead of standard space.
However the above $1 variable doesn't work for me. It inserts text "$1 " instead of a part of original matched string + nbsp.
What is the reason for the observed behaviour? Is there any other way to achieve it?
$1 doesn't work because you don't have any capturing subgroups.
The regular expression should be something like /\b(\w+)\s+/.
Seems you want to do something like this:
myString.replace(/\s(\w)\s/,"$1\xA0");
but that way you will loose the whitespace before your single-letter word. So you probably want to also include the first \s in the capturing group.

Help interpreting a javascript Regex

I have found the following expression which is intended to modify the id of a cloned html element e.g. change contactDetails[0] to contactDetails[1]:
var nel = 1;
var s = $(this).attr(attribute);
s.replace(/([^\[]+)\[0\]/, "$1["+nel+"]");
$(this).attr(attribute, s);
I am not terribly familiar with regex, but have tried to interpret it and with the help of The Regex Coach however I am still struggling. It appears that ([^\[]+) matches one or more characters which are not '[' and \[0\]/ matches [0]. The / in the middle I interpret as an 'include both', so I don't understand why the author has even included the first expression.
I dont understand what the $1 in the replace string is and if I use the Regex Coach replace functionality if I simply use [0] as the search and 1 as the replace I get the correct result, however if I change the javascript to s.replace(/\[0\]/, "["+nel+"]"); the string s remains unchanged.
I would be grateful for any advice as to what the original author intended and help in finding a solution which will successfully replace the a number in square brackets anywhere within a search string.
Find
/ # Signifies the start of a regex expression like " for a string
([^\[]+) # Capture the character that isn't [ 1 or more times into $1
\[0\] # Find [0]
/ # Signifies the end of a regex expression
Replace
"$1[" # Insert the item captured above And [
+nel+ # New index
"]" # Close with ]
To create an expression that captures any digit, you can replace the 0 with \d+ which will match a digit 1 or more times.
s.replace(/([^\[]+)\[\d+\]/, "$1["+nel+"]");
The $1 is a backreference to the first group in the regex. Groups are the pieces inside (). So, in this case $1 will be replaced by whatever the ([^\[]+) part matched.
If the string was contactDetails[0] the resulting string would be contactDetails[1].
Note that this regex only replaces 0s inside square brackets. If you want to replace any number you will need something like:
([^\[]+)\[\d+\]
The \d matches any digit character. \d+ then becomes any sequence of at least one digit.
But your code will still not work, because Javascript strings are immutable. That means they can't be changed once created. The replace method returns a new string, instead of changing the original one. You should use:
s = s.replace(...)
looks like it replaces arrays of 0 with 1.
For example: array[0] goes to array[1]
Explanation:
([^[]+) - This part means save everything that is not a [ into variable $1
[0]/ - This part limits Part 1 to save everything up to a [0]
"$1["+nel+"]" - Print out the contents of $1 (loaded from part 1) and add the brackets with the value of nel. (in your example nel = 1)
Square braces define a set of characters to match. [abc] will match the letters a, b or c.
By adding the carat you are now specifying that you want characters not in the set. [^abc] will match any character that is not an a, b or c.
Because square braces have special meaning in RegExps you need to escape them with a slash if you want to match one. [ starts a character set, \[ matches a brace. (Same concept for closing braces.)
So, [^\[]+ captures 1 or more characters that are not [.
Wrapping that in parenthesis "captures" the matched portion of the string (in this case "contactDetails" so that you can use it in the replacement.
$1 uses the "captured" string (i.e. "contactDetails") in the replacement string.
This regex matches "something" followed by a [0].
"something" is identified by the expression [^\[]+ which matches all charactes that are not a [. You can see the () around this expression, because the match is reused with $1, later. The rest of your regex - that is \[0\] just matches the index [0]. The author had to write \[ and \] because [ and ] are special charactes for regular expressions and have to be escaped.
$1 is a reference to the value of the first paranthesis pair. In your case the value of
[^\[]+
which matches one or more characters which are not a '['
The remaining part of the regexp matches string '[0]'.
So if s is 'foobar[0]' the result will be 'foobar[1]'.
[^\[] will match any character that is not [, the '+' means one or more times. So [^[]+ will match contactDetails. The brackets will capture this for later use. The '\' is an escape symbol so the end \[0\] will match [0]. The replace string will use $1 which is what was captured in the brackets and add the new index.
Your interpretation of the regular expression is correct. It is intended to match one or more characters which are not [, followed by a literal [0]. And used in the replace method, the match would be replaced with the match of the first grouping (that’s what $1 is replaced with) together with the sequence [ followed by the value of nel and ] (that’s how "$1["+nel+"]" is to be interpreted).
And again, a simple s.replace(/\[0\]/, "["+nel+"]") does the same. Except if there is nothing in front of [0], because in that case the first regex wouldn’t find a match.

Categories