Regex to add a new line break after each bracket - javascript

I have tried using replace with regex (/\([(]\)/g,'\1\n') but its not helping. Any help?

Regardless what the language is, a round bracket matching pattern is either \( or [(]. If you need to use a whole match value in the replacement, there are $& or $0 backreferences.
Thus, search for /[(]/g (you may add more chars into the character class, like [()\][]...) and replace with "$&\n" (or "$0\n").
See the regex demo.
A JS demo:
var regex = /[(]/g;
var str = "before(after and before 1(after1";
var subst = "$&\n";
var result = str.replace(regex, subst);
console.log(result);

Related

Replace multiple characters by one character with regex

I have this string :
var str = '#this #is____#a test###__'
I want to replace all the character (#,_) by (#) , so the excepted output is :
'#this #is#a test#'
Note :
I did not knew How much sequence of (#) or (_) in the string
what I try :
I try to write :
var str = '#this #is__ __#a test###__'
str = str.replace(/[#_]/g,'#')
alert(str)
But the output was :
#this #is## ###a test#####
my try online
I try to use the (*) for sequence But did not work :
var str = '#this #is__ __#a test###__'
str = str.replace(/[#_]*/g,'#')
alert(str)
so How I can get my excepted output ?
A well written RegEx can handle your problem rather easily.
Quoting Mohit's answer to have a startpoint:
var str = '#this #is__ __#a test###__';
var formattedStr = str.replace(/[#_,]+/g, '#');
console.log( formattedStr );
Line 2:
Put in formattedStr the result of the replace method on str.
How does replace work? The first parameter is a string or a RegEx.
Note: RegExps in Javascripts are Objects of type RegExp, not strings. So writing
/yourRegex/
or
New RegExp('/yourRegex/')
is equivalent syntax.
Now let's discuss this particular RegEx itself.
The leading and trailing slashes are used to surround the pattern, and the g at the end means "globally" - do not stop after the first match.
The square parentheses describe a set of characters who can be supplied to match the pattern, while the + sign means "1 or more of this group".
Basically, ### will match, but also # or #####_# will, because _ and # belong to the same set.
A preferred behavior would be given by using (#|_)+
This means "# or _, then, once found one, keep looking forward for more or the chosen pattern".
So ___ would match, as well as #### would, but __## would be 2 distinct match groups (the former being __, the latter ##).
Another problem is not knowing wheter to replace the pattern found with a _ or a #.
Luckily, using parentheses allows us to use a thing called capturing groups. You basically can store any pattern you found in temporary variabiles, that can be used in the replace pattern.
Invoking them is easy, propend $ to the position of the matched (pattern).
/(foo)textnotgetting(bar)captured(baz)/ for example would fill the capturing groups "variables" this way:
$1 = foo
$2 = bar
$3 = baz
In our case, we want to replace 1+ characters with the first occurrence only, and the + sign is not included in the parentheses!
So we can simply
str.replace("/(#|_)+/g", "$1");
In order to make it work.
Have a nice day!
Your regex replaces single instance of any matched character with character that you specified i.e. #. You need to add modifier + to tell it that any number of consecutive matching characters (_,#) should be replaced instead of each character individually. + modifier means that 1 or more occurrences of specified pattern is matched in one go. You can read more about modifiers from this page:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
var str = '#this #is__ __#a test###__';
var formattedStr = str.replace(/[#_,]+/g, '#');
console.log( formattedStr );
You should use the + to match one-or-more occurrences of the previous group.
var str = '#this #is__ __#a test###__'
str = str.replace(/[#_]+/g,'#')
alert(str)

Give priority to group inside regular expression

I want my output to be what's inside var data = "THIS";, to do so I've manage to do this:
var plaintext = fs.readFileSync( process.argv[ 1 ] ).toString();
var regex = new RegExp("var\\ data\\ =\\ \"(.{0,})\";", "g", "y");
var regex2 = new RegExp("\"(.{0,})\"", "g");
var info = JSON.parse(plaintext.match(regex)[0].match(regex2)[0]);
Is there any way to have only one regular expression, and compact the code into 2 or 3 lines?
How about this?
plaintext.match(/var\s+data\s*=\s*"(.*)";/)[1]
Update: This regex will also match strings that contain escaped quotes, e.g. "\"foo\"" as long as these quotes aren't followed by a semicolon. For this to work, the closing quote must be immediately followed by a semicolon.
As an alternative, you could also exclude double quotes from the matched string (Use [^"]* instead of .*) and leave out the semicolon from the regular expression.
Here is my approach:
var matches = plaintext.match(/var data = "([^"]+)"/);
https://jsfiddle.net/7hy8epp5/

JS: Adding a space between Japanese character phrase and number using regex

I need to add a space between all instances of the Japanese 丁目(chome) that are directly followed a number of unspecified digit length.
ex: 北23条東12丁目5-30-405
I have tried this (where s = "北23条東12丁目5-30-405")
s.replace(/(?:丁目)+\d+/g, "$1 ")
Since I want to add a space after a non-captured group, I thought a $1 was in order, but I am not sure how to write it (IF this replace method were to work it would probably literally output "$1 ").
Needless to say, my attempted replace() method does not work
(desired output: "北23条東12丁目 5-30-405")(<-- space after 丁目)
I'm not suprised this doesn't work... can I get pointed in the right direction?
s.replace(/(丁目)(?=\d)/g, "$1 ")
This should do it for you.Your earlier regex was not working cos if ?: which makes it non capturing and $1 had nothing in it.See demo.
https://regex101.com/r/nS2lT4/10
var re = /(丁目)(?=\d)/g;
var str = '北23条東12丁目5-30-405';
var subst = '$1 ';
var result = str.replace(re, subst);

Reduce multiple occurences of any non-alphanumeric characters in string down to one, **NOT REMOVE**

I've been searching for a solution but almost every one that I've come across with is about replacing a matching pattern with a previously known character.
For example:
var str = 'HMQ 2.. Elizabeth';
How do we catch multiple occurences of that dots in the string and replace them with only one? And it's also not specific to dots but any non-alphanumeric characters that we don't know which. Thank you.
Use a backreference. \1 in the regex refers to the first match group in the expression.
var str = 'HMQ 2.. Elizabetttth .';
var regex = /([^A-Za-z0-9])\1+/g;
var trimmed = str.replace(regex, "$1");
console.log( trimmed );

Javascript Replace, string with comma

I have a string that contains multiple occurrences of ],[ that I want to replace with ]#[
No matter what I try I cant get it right.
var find = '],[';
var regex = new RegExp(find, "g");
mytext.replace(regex, ']#[')
Doesn't work
mytext = mytext.replace(/],[/g,']#[');
Doesn't work
Any idea where I am going wrong?
The answer is that [ and ] are special characters in the context of regular expressions and as such need to be escaped either by means of \ i.e. to match ] you write [ when you use the convenient Javascript shorthand for regular expressions that you can find in the code below:
var regex= /\],\[/g
var result = mytext.replace(regex, ']#[')
Please check out the following jsFiddle: http://jsfiddle.net/JspRR/4/
As you can see the important bit is escaping the ] and the [ when constructing the regular expression.
Now if you did not want to use the Javascript regular expressions shorthand, you would still need to have the same escaping. However, in that case the \ character will need to be escaped itself ( ... by itself!)
var regex = new RegExp("\\],\\[", "g");
var result = mytext.replace(regex, ']#[')
The reason your example doesn't work is because normally square brackets represents a character class and therefore you need to escape them like so
var find = '\\],\\[';
var regex = new RegExp(find, "g");
mytext.replace(regex, ']#[')
You can also use a regex literal
mytext.replace(/\],\[/g, "]#[");
Try this:-
mytext.replace(/\],\[/g, ']#[')
Square brackets are special characters inside a regular expression: they are used to define a character set.
If you want to match square brackets in a regexp, you have to escape them, using back slash.
"[1],[2],[3]".replace(/\],\[/g, "]#[");
Or, in case you use the builtin constructor:
"[1],[2],[3]".replace(new RegExp("\\],\\[", "g"), "]#[");
In both case we have to use the g flag so that the regular expression can match all the occurrences of the searched string.
var str = "[1],[2],[3]";
console.log(str.replace(/\],\[/g, "]#["));
console.log(str.replace(new RegExp("\\],\\[", "g"), "]#["));
var str = "[1],[2],[3]";
var replaced = str.replace('],[', ']#[');

Categories

Resources