can i improve this "regex"? - javascript

I have the following string:
const myString = '"{{ some text here }}"'
I want to remove the quotes before {{ and after }}. I can do:
myString.replace('"{{', '{{').replace('}}"', '}}')
But I'm wondering if there is a better way to achieve this without calling replace twice?
Does anyone can let me know if there is a better way and explain?
http://jsbin.com/xafovamihi/edit?js,console

You may use a regex with an alternation group where you can capture {{ and }} into Group 1 and 2 respectively and replace with the backreferences only:
var myString = '"{{ some text here }}"';
console.log(myString.replace(/"({{)|(}})"/g, '$1$2'))
Details:
"({{) - matches " and captures {{ into Group 1
| - or
(}})" - captures }} into Group 2 and matches "
Since the replacement backreferences, when referencing a group that did not participate in the match, are initialized with an empty string, this $1$2 replacement will work properly all the time.
The global modifier /g will ensure all matches are replaced.

An easy way would be to combine the two patterns into one match using regex OR, so you get /"{{|}}"/g

Why not to use regex to find {{ with }} and any text between?
const myString = '"{{ some text here }}"',
reg = /{{.*?}}/;
console.log(myString.match(reg)[0]);

Related

Get values inside double curly braces with regex

From this string:
dfasd {{test}} asdhfj {{te{st2}} asdfasd {{te}st3}}
I would like to get the following substrings:
test, te{st2, te}st3
In other words I want keep everything inside double curly braces including single curly braces.
I can't use this pattern:
{{(.*)}}
because it matches the whole thing between first {{ and last }}:
test}} asdhfj {{te{st2}} asdfasd {{te}st3
I managed to get the first two with this regex pattern:
{{([^}]*)}}
Is there any way to get all three using regex?
Try {{(.*?)}}.
.*? means to do a lazy / non greedy search => as soon as }} matches, it will capture the found text and stop looking. Otherwise it will do a greedy search and therefore start with the first {{ and end with the very last }}.
This isn't that pretty, but it doesn't use RegEx and makes it clear what you are trying to accomplish.
const testString = 'dfasd {{test}} asdhfj {{te{st2}} asdfasd {{te}st3}}';
const getInsideDoubleCurly = (str) => str.split('{{')
.filter(val => val.includes('}}'))
.map(val => val.substring(0, val.indexOf('}}')));
console.log(getInsideDoubleCurly(testString));

How to replace & and space from a string Angular

I am trying to replace '&' and 'space' from a string.
I can remove the space by string.replace(/[\s]/g, '');
and remove the special character & by string.replace(/[^\da-zA-Z]/g, '')
Can I use both regex in one code? for removing special charecters and space from the string.
Use | to "or" regexes, e.g.
/(\s|&)/g
Grouping via (...) can be necessary to scope what gets or'd.
In this case, you just have two selectors, so it should work without as well.
/\s|&/g
Combine regex for & and space /[& ]+/g
var str='abzx12& 1'
console.log(str.replace(/[& ]+/g,''));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here you go with one more solution
.replace(/ |&/g,'')
Example
var a = "asdasdas dsadasdas dasdas asdas & dasdasd &&&&";
console.log(a.replace(/ |&/g,''));
Try this if you don't want to use regex.
var str = "abc def & ghi jkl & mno";
console.log(str.split(' ').join('').split('&').join(''));
first replace space with null and than replace '&' with null.
It might be help you.

Using a split with a regex not replacing correctly?

I'm trying to parse rows of text in order to retrive the 4 version numbers:
v.1.7.600.0 - latest | 9.2.6200.0 to 9.2.9999
I'm looking to be able to parse a line like this into:
['v.1.7.600.0', 'latest', '9.2.6200.0', '9.2.9999']
At the moment, I have something like this:
var line = "v.1.7.600.0 - latest | 9.2.6200.0 to 9.2.9999"
var result = line.split(/ (\||-|to) /g)
console.log(result)
I'm not that great at regex but it matches so i'm not sure why it includes them in the result.
You are almost there, just use a non-capturing group:
var line = "v.1.7.600.0 - latest | 9.2.6200.0 to 9.2.9999";
var result = line.split(/\s+(?:\||-|to)\s+/);
console.log(result);
You need a non-capturing group because split() will extract captured values into the resulting array.
Also, it might be more convenient to match one or more whitespaces with \s+ rather than using a literal space.
Besides, the /g modifier is redundant with split(), it the default behavior.
You also may define a character class for single char delimiters, and write a bit more compact /\s+(?:[|-]|to)\s+/ regex.

javascript regular expression ignore condition between the text

I have a text for example as below:
"head1>data1,data2,data3|head2>data1,data2,data3|head3>data3,data4,data5**
now I want to replace ">data1..|" with "|"
I am using this: ".replace(/>\S+\||>\S+$/g,"|");"
But this is not helping as it gives me data as below:
"head1|head3|" instead of "head1|head2|head3|"
I am unable to find the right method.
You can use
>\S+?(?:\||$)
See the regex demo
The point is to make \S+ lazy, and to shorten the pattern we can use place the >\S+? before the alternation group.
Pattern details:
>\S+? - a literal > followed with 1+ non-whitespace symbols but as few as possible up to
(?:\||$) - a literal | or the end of string.
A simple approach :), was trying like this
var str = "head1>data1,data2,data3|head2>data1,data2,data3|head3>data3,data4,data5";
console.log(str.replace(/>[a-z1-9,]+/g,"|").replace(/\|+/g, "|"));
>[a-z1-9,]+ will select >data1,data2,data3
and then replaced multiple | with single |
:)
You can use:
>[a-z0-9,]+\|
and then replace this with single | every time.

A (simple?) RegEx question for global non capturing groups

Say I have the string Hello {{name}}, how are you doing today? I'm trying to grab name from that string.
So far, I have /\{{2}[a-z0-9]*\}{2}/gi. The problem, is, it grabs {{name}} and not name. Without the global flag it works fine, but I'm trying to get every instance of words within double brackets, so it's not quite right... I'm no RegEx pro so I'm hoping someone can help me out...
The best solution would be to use lookaround assertions so the {{ and }} don't get picked up, however JavaScript regex doesn't support lookbehind, it only supports lookahead.
So one alternative is to place your text in a capture group and grab what's inside:
/\{{2}([a-z0-9]*)\}{2}/gi
To get every capture, make a RegExp object with your regex, and iterate through the results of its exec() function. For example:
var str = 'Hello {{name}}, how are you doing {{date}}?';
var re = /\{{2}([a-z0-9]*)\}{2}/gi;
var words = [];
var match;
while (match = re.exec(str)) {
words.push(match[1]);
}
jsFiddle sample
Or as Gumbo suggests in his comment, manually strip out the {{ and }} from your array of matches.
Yea as mentioned, pattern matching on the 2 opening and closing braces is the way to go (assuming the name does not have curly braces in succession of the number of 2 within itself, either opening/closing)
/\{{2}([a-z0-9]+)*\}{2}/gi

Categories