javascript regex replace spaces between brackets - javascript

How can I use JS regex to replace all occurences of a space with the word SPACE, if between brackets?
So, what I want is this:
myString = "a scentence (another scentence between brackets)"
myReplacedString = myString.replace(/*some regex*/)
//myReplacedString is now "a scentence (anotherSPACEscentenceSPACEbetweenSPACEbrackets)"
EDIT:
what I've tried is this (I'm quite new to regular expressions)
myReplacedString = myString.replace(/\(\s\)/, "SPACE");

You could perhaps use the regex:
/\s(?![^)]*\()/g
This will match any space without an opening bracket ahead of it, with no closing bracket in between the space and the opening bracket.
Here's a demo.
EDIT: I hadn't considered cases where the sentences don't end with brackets. The regexp of #thg435 covers it, however:
/\s(?![^)]*(\(|$))/g

I'm not sure about one regex, but you can use two. One to get the string inside the (), then another to replace ' ' with 'SPACE'.
myReplacedString = myString.replace(/(\(.*?\))/g, function(match){
return match.replace(/ /g, 'SPACE');
});

Related

replace single quote in middle of string using regex

Have a string:
stringName= "'john's example'"
Need to do a string.replace to remove the single quote in the middle of the string, not the first and last otherwise will break my javascript
have tried stringName.replace("/.'./","") to replace only the single quote in the middle of the string but does not work
Help is very appreciated! :)
Use (^'|'$)|' as matching regular expression:
stringName = "'john's e'xam'ple'";
console.log(
stringName.replace(/(^'|'$)|'/g, '$1')
);
First thing is you aren't doing a regex replace, you are replacing a string which looks like /.'./ (because of the " in the first argument). Secondly, the regex you're doing is only going to be looking for a single character (.) then a single quote, then another character. What you might want to do is something like stringName.replace(/(.+)'(.+)/, "$1$2")
Use split, join after stripping of first and last character
var f1 = (str) => str.charAt(0) + str.split("'").join("") + str.slice(-1);
f1( "'john's exa''mp'le'" ); //'johns example'

javascript replace all occurrences ",\S" with ", \S"

I want to have spaces separating items in a CSV string. That is "123,456,789" => "123, 456, 789". I have tried, but been unable to construct a regexp to do this. I read some postings and thought this would to the trick, but no dice.
text = text.replace(new RegExp(",\S", "g"), ", ");
Could anyone show me what I am doing wrong?
You have two problems:
Backslashes are a pain in the, um, backslash; because they have so many meanings (e.g. to let you put a quote-mark inside a string), you often end up needing to escape the backslash with another backslash, so you need ",\\S" instead of just ",\S".
The \S matches a character other than whitespace, so that character gets removed and replaced along with the comma. The easiest way to deal with that is to "capture" it (by putting it in parentheses), and put it back in again in the replacement (with $1).
So what you end up with is this:
text = text.replace(new RegExp(',(\\S)', "g"), ", $1");
However, there is a slightly neater way of writing this, because JavaScript lets you write a regex without having a string, by putting it between slashes. Conveniently, this doesn't need the backslash to be escaped, so this much shorter version works just as well:
text = text.replace(/,(\S)/g, ", $1");
As an alternative to capturing, you can use a "zero-width lookahead", which in this situation basically means "this bit has to be in the string, but don't count it as part of the match I'm replacing". To do that, you use (?=something); in this case, it's the \S that you want to "look ahead to", so it would be (?=\S), giving us this version:
text = text.replace(/,(?=\S)/g, ", ");
There are 2 mistakes in your code:
\S in a string literal translates to just S, because \S is not a valid escape sequence. As such, your regex becomes /,S/g, which doesn't match anything in your example. You can escape the backslash (",\\S") or use a regex literal (/,\S/g).
After this correction, you will replace the character following the comma with a space. For instance, 123,456,789 becomes 123, 56, 89. There are two ways to fix this:
Capture the non-space character and use it in the replacement expression:
text = text.replace(/,(\S)/g, ', $1')
Use a negative lookahead assertion (note: this also matches a comma at the end of the string):
text = text.replace(/,(?!\s)/g, ', ')
text = text.replace(/,(\S)/g, ', $1');
try this:
var x = "123,456,789";
x = x.replace(new RegExp (",", "gi"), ", ");

I can't replace properly with javascript and regex

I have this string:
var value = recordsArray_f006b490[]=1&recordsArray_9715b841[]=1&recordsArray_afb085e2[]=1&recordsArray_fc542e23[]=1&recordsArray_19490084[]=1&recordsArray_615a5055[]=1&recordsArray_32841aa6[]=1&recordsArray_a02a35c7[]=1&recordsArray_d32b5b88[]=1&recordsArray_d32d5339[]=1&recordsArray_56c2b8e10[]=1&recordsArray_8ce9f4211[]=1&recordsArray_5a87afc12[]=1&recordsArray_2b13c0113[]=1&recordsArray_afb085e14[]=1&recordsArray_51db9f216[]=1&recordsArray_2a7470415[]=1&recordsArray_d51057a17[]=1&recordsArray_b274ee918[]=1&recordsArray_d0812dd19[]=1&recordsArray_b1ede8920[]=1&recordsArray_9d76ae821[]=1&recordsArray_0ae779d22[]=1&recordsArray_871777923[]=1&recordsArray_9e22c9f24[]=220236&recordsArray_787c57e25[]=220236&recordsArray_499e25726[]=1&recordsArray_a0600da27[]=220236&recordsArray_9ef1fca28[]=220236&recordsArray_67eee1929[]=220236&recordsArray_24c3a0b30[]=220236&recordsArray_5d2090831[]=220236
And I want to replace "[]=" with "_" and I have the next javascript code:
var regex = new RegExp("[]=", "g");
alert(value.replace(regex, "_"));
but it doesnt change anything, how can I do it? Thanks!
Escape the first [ to indicate its not defining a character class;
var regex = new RegExp("\\[]=", "g");
Square brackets are reserved in regex. You need to escape them for matching
var regex = new RegExp("\\[\\]=", "g");
escape the brackets as they has special meaning.
var regex = new RegExp("\\[\\]=", "g");
As others have noted, you need to escape the square brackets, as they have special meaning in regex. I want to note, also, that the most clear and terse way to do this is with JavaScript's regex literal notation:
var regex = /\[]=/g;
You also only need to escape the opening [ bracket. Closing brackets (the ] character) only have a special meaning inside a character class, just as [ only has special meaning outside one.
You can't include brackets in regexp. Use \\[ for this.

How can I put [] (square brackets) in RegExp javascript?

I'm trying this:
str = "bla [bla]";
str = str.replace(/\\[\\]/g,"");
console.log(str);
And the replace doesn't work, what am I doing wrong?
UPDATE: I'm trying to remove any square brackets in the string,
what's weird is that if I do
replace(/\[/g, '')
replace(/\]/g, '')
it works, but
replace(/\[\]/g, ''); doesn't.
It should be:
str = str.replace(/\[.*?\]/g,"");
You don't need double backslashes (\) because it's not a string but a regex statement, if you build the regex from a string you do need the double backslashes ;).
It was also literally interpreting the 1 (which wasn't matching). Using .* says any value between the square brackets.
The new RegExp string build version would be:
str=str.replace(new RegExp("\\[.*?\\]","g"),"");
UPDATE: To remove square brackets only:
str = str.replace(/\[(.*?)\]/g,"$1");
Your above code isn't working, because it's trying to match "[]" (sequentially without anything allowed between). We can get around this by non-greedy group-matching ((.*?)) what's between the square brackets, and using a backreference ($1) for the replacement.
UPDATE 2: To remove multiple square brackets
str = str.replace(/\[+(.*?)\]+/g,"$1");
// bla [bla] [[blaa]] -> bla bla blaa
// bla [bla] [[[blaa] -> bla bla blaa
Note this doesn't match open/close quantities, simply removes all sequential opens and closes. Also if the sequential brackets have separators (spaces etc) it won't match.
You have to escape the bracket, like \[ and \]. Check out http://regexpal.com/. It's pretty useful :)
To replace all brackets in a string, this should do the job:
str.replace(/\[|\]/g,'');
I hope this helps.
Hristo
Here's a trivial example but worked for me. You have to escape each sq bracket, then enclose those brackets within a bracket expression to capture all instances.
const stringWithBrackets = '[]]][[]]testing][[]][';
const stringWithReplacedBrackets = stringWithBrackets.replace(/[\[\]]/g, '');
console.log(stringWithReplacedBrackets);
Two backslashes produces a single backslash, so you're searching for "a backslash, followed by a character class consisting of a 1 or a right bracket, and then you're missing an closing bracket.
Try
str.replace(/\[1\]/g, '');
What exactly are you trying to match?
If you don't escape the brackets, they are considered character classes. This:
/[1\\]/
Matches either a 1 or a backslash. You may want to escape them with one backslash only:
/\[1\]/
But this won't match either, as you don't have a [1] in your string.
I stumbled on this question while dealing with square bracket escaping within a character class that was designed for use with password validation requiring the presence of special characters.
Note the double escaping:
var regex = new RegExp('[\\]]');
As #rudu mentions, this expression is within a string so it must be double escaped. Note that the quoting type (single/double) is not relevant here.
Here is an example of using square brackets in a character class that tests for all the special characters found on my keyboard:
var regex = new RegExp('[-,_,\',",;,:,!,#,#,$,%,^,&,*,(,),[,\\],\?,{,},|,+,=,<,>,~,`,\\\\,\,,\/,.]', 'g')
How about the following?
str = "bla [bla]";
str.replace(/[[\\]]/g,'');
You create a character set with just the two characters you are interested in and do a global replace.
Nobody quite made it simple and correct:
str.replace(/[[\]]/g, '');
Note the use of a character class, with no escape for the open bracket, and a single backslash escape for the close bracket.

Brackets in Regular Expression

I'd like to compare 2 strings with each other, but I got a little problem with the Brackets.
The String I want to seek looks like this:
CAPPL:LOCAL.L_hk[1].vorlauftemp_soll
Quoting those to bracket is seemingly useless.
I tried it with this code
var regex = new RegExp("CAPPL:LOCAL.L_hk\[1\].vorlauftemp_soll","gi");
var value = "CAPPL:LOCAL.L_hk[1].vorlauftemp_soll";
regex.test(value);
Somebody who can help me??
It is useless because you're using string. You need to escape the backslashes as well:
var regex = new RegExp("CAPPL:LOCAL.L_hk\\[1\\].vorlauftemp_soll","gi");
Or use a regex literal:
var regex = /CAPPL:LOCAL.L_hk\[1\].vorlauftemp_soll/gi
Unknown escape characters are ignored in JavaScript, so "\[" results in the same string as "[".
In value, you have (1) instead of [1]. So if you expect the regular expression to match and it doesn't, it because of that.
Another problem is that you're using "" in your expression. In order to write regular expression in JavaScript, use /.../g instead of "...".
You may also want to escape the dot in your expression. . means "any character that is not a line break". You, on the other hand, wants the dot to be matched literally: \..
You are generating a regular expression (in which [ is a special character that can be escaped with \) using a string (in which \ is a special character).
var regex = /CAPPL:LOCAL.L_hk\[1\].vorlauftemp_soll/gi;

Categories

Resources