javascript REGex remove single quote in match - javascript

var RegTxt = "$f1$='test' AND f2='test2'";
alert(RegTxt.match(/\'[^\']*'/g))
returns the match correctely i:e 'test','test2' but how can i remove the single quote in the match.

This would be quite simple if JavaScript supported negative lookbehinds:
/(?<=').*?(?=')/
But unfortunately, it doesn't.
In cases like these I like to abuse String.prototype.replace:
// btw, RegTxt should start with a lowercase 'r', as per convention
var match = [];
regTxt.replace(/'([^']*)'/g, function($0, $1){
match.push($1);
});
match; // => ['test', 'test2']

Here is a crude solution to your problem.
var match = RegTxt.match(/\'[^\']*'/g)
match = match.substring(1, match.length - 2);

Trivial approach:
RegTxt.replace(/'/g, "")
using your regex:
RegTxt.replace(/\'([^\']*)'/g, "$1")

var matches = str.match(regex);
var newMatches = [];
for( i in matches )
{
var word = matches[i];
newMatches.push( word.substring(1,word.length-1))
}
newMatches will now contain the array you need.

Related

Javascript regex capture giving unexpected results

I am trying to capture all data before the first _. What I have so far is
const regex = /(.*)(?=_)/g;
var s = "Mike_Jones_Jr";
console.log(s.match(regex));
The output is an array Array ["Mike_Jones","" ]
What I was expecting was Mike
Use /^[^_]*/
^ looks from the beginning of the string
[^_] negates the _
* gives any number of characters
const regex = /^[^_]*/;
var s = "Mike_Jones_Jr";
console.log(s.match(regex));
var s = "Mike_Jones_Jr";
console.log(s.split('_')[0]);
Create a capture group ((something between parentheses)) that starts at the beginning of the line (^) and is lazy (.*?), then grab the second item in the matching array.
const regex = /(^.*?)_/s
console.log('Mike_Jones_Jr'.match(regex)[1] || '')
console.log(`Mike
_Jones_Jr`.match(regex)[1] || '')
You can simply use split,
Note:- Second parameter is to limit the number of elements in final outptut
var s = "Mike_Jones_Jr";
console.log( s.split('_', 1) );
If you want to do using regex, you can drop the g flag
const regex = /^[^_]*(?=_)/;
var s = "Mike_Jones_Jr";
console.log(s.match(regex));
console.log("_ melpomene is awesome".match(regex));

Find every instance of #<username> in paragraph in Javascript

I have a paragraph that could have 1 or more instances of "#" followed by different usernames. How can I find each instance of this in Javascript?
Something like this but it doesn't work yet:
var regexp = '/#([a-z0-9_]+)/i';
var post = "Hi #tom, where is #john and #nick?" ;
var match, matches = [];
while ((match = regexp.exec(post)) != null) {
matches.push(match.index);
}
console.log(matches);
Console log would read: #tom #john #nick
You have two mistakes in your code causing it not to work as you expect.
(1.) You need to remove the quotes from your regular expression and use the g (global) modifier. You can replace your character class to the shorter version \w and remove the case-insensitive modifier here.
var regexp = /#\w+/g
(2.) You need to reference the match instead of referencing the match.index
matches.push(match[0]);
Final solution:
var post = "Hi #tom, where is #john and #nick?";
var regexp = /#\w+/g
var match, matches = [];
while ((match = regexp.exec(post)) != null) {
matches.push(match[0]);
}
console.log(matches); //=> [ '#tom', '#john', '#nick' ]
Alternatively you can use the String.match method.
var post = 'Hi #tom, where is #john and #nick?',
result = post.match(/#\w+/g);
console.log(result); //=> [ '#tom', '#john', '#nick' ]

Display characters other than alphabets using reqular expression

I have tried to display characters other than alphabets in the particular string but it is displaying only the first char.
var myArray = /[^a-zA-Z]+/g.exec("cdAbb#2547dbsbz78678");
The reason it is only displaying the first character is because with using exec and the g modifier (global), this method is meant to be used in a loop for getting all sub matches.
var str = "cdAbb#2547dbsbz78678";
var re = /[^a-zA-Z]+/g;
var myArray;
while (myArray = re.exec(str)) {
console.log(myArray[0]);
}
Output
#2547
78678
If you were wanting to combine the matches you could use the following.
var str = "cdAbb#2547dbsbz78678",
res = str.match(/[\W\d]+/g).join('');
# => "#254778678"
Or do a replacement
str = str.replace(/[a-z]+/gi, '');
You can do:
"cdAbb#2547dbsbz78678".match(/[^a-zA-Z]+/g).join('');
//=> #254778678
RegExp.exec with g (global) modifier needs to run in loop to give you all the matches.

Using Regex to pull out a part of a string

I can't figure out how to pull out multiple matches from the following example:
This code:
/prefix-(\w+)/g.exec('prefix-firstname prefix-lastname');
returns:
["prefix-firstname", "firstname"]
How do I get it to return:
[
["prefix-firstname", "firstname"],
["prefix-lastname", "lastname"]
]
Or
["prefix-firstname", "firstname", "prefix-lastname", "lastname"]
This will do what you want:
var str="prefix-firstname prefix-lastname";
var out =[];
str.replace(/prefix-(\w+)/g,function(match, Group) {
var row = [match, Group]
out.push(row);
});
Probably a mis-use of .replace, but I don't think you can pass a function to .match...
_Pez
Using a loop:
re = /prefix-(\w+)/g;
str = 'prefix-firstname prefix-lastname';
match = re.exec(str);
while (match != null) {
match = re.exec(str);
}
You get each match one at a time.
Using match:
Here, the regex will have to be a bit different, because you cannot get sub-captures (or I don't know how to do it with multiple matches)...
re = /[^\s-]+(?=\s|$)/g;
str = 'prefix-firstname prefix-lastname';
match = str.match(re);
alert(match);
[^\s-]+ matches all characters except spaces and dashes/hyphens only if they are followed by a space or are at the end of the string, which is a confition imposed by (?=\s|$).
You can find the groups in two steps:
"prefix-firstname prefix-lastname".match(/prefix-\w+/g)
.map(function(s) { return s.match(/prefix-(\w+)/) })

Regex remove repeated characters from a string by javascript

I have found a way to remove repeated characters from a string using regular expressions.
function RemoveDuplicates() {
var str = "aaabbbccc";
var filtered = str.replace(/[^\w\s]|(.)\1/gi, "");
alert(filtered);
}
Output: abc
this is working fine.
But if str = "aaabbbccccabbbbcccccc" then output is abcabc.
Is there any way to get only unique characters or remove all duplicates one?
Please let me know if there is any way.
A lookahead like "this, followed by something and this":
var str = "aaabbbccccabbbbcccccc";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "abc"
Note that this preserves the last occurrence of each character:
var str = "aabbccxccbbaa";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "xcba"
Without regexes, preserving order:
var str = "aabbccxccbbaa";
console.log(str.split("").filter(function(x, n, s) {
return s.indexOf(x) == n
}).join("")); // "abcx"
This is an old question, but in ES6 we can use Sets. The code looks like this:
var test = 'aaabbbcccaabbbcccaaaaaaaasa';
var result = Array.from(new Set(test)).join('');
console.log(result);

Categories

Resources