Javascript regex ending word not found - javascript

In this regex , I need to match an ending word that starts with '(', ')' or ','.
Regex :
/[\(\),].*$/
For example, given the text (aaa,bbb)ccc I need to obtain )ccc. Still, it returns the entire text. What's wrong with this regex?

You can use:
'(aaa,bbb)ccc'.match(/[(),][^(),]+$/)
//=> [")ccc"]
[^(),]+ is negation pattern that matches any character but any listed in [^(),].
Problem with [(),].*$ is that it matches very first ( in input and matches till end.

You can also consider using capturing group while consuming all the characters up to the first (, ) or ,:
.*([(),].*)$
.* will consume as many characters as it can, then any character in this character class [(),], and then the rest of the characters up to the end.
The )ccc value will be stored in Group 1:
var re = /.*([(),].*)$/;
var str = '(aaa,bbb)ccc';
if ((m = re.exec(str)) !== null) {
document.getElementById("res").innerHTML = m[1];
}
<div id="res"/>

Try this regex:
/[(,)][^(,)]*$/

Related

Javascript - Regex - how to filter characters that are not part of regex

I want to accept words and some special characters, so if my regex
does not fully match, let's say I display an error,
var re = /^[[:alnum:]\-_.&\s]+$/;
var string = 'this contains invalid chars like ##';
var valid = string.test(re);
but now I want to "filter" a phrase removing all characters not matching the regex ?
usualy one use replace, but how to list all characters not matching the regex ?
var validString = string.filter(re); // something similar to this
how do I do this ?
regards
Wiktor Stribiżew solution works fine :
regex=/[^a-zA-Z\-_.&\s]+/g;
let s='some bloody-test #rfdsfds';
s = s.replace(/[^\w\s.&-]+/g, '');
console.log(s);
Rajesh solution :
regex=/^[a-zA-Z\-_.&\s]+$/;
let s='some -test #rfdsfds';
s=s.split(' ').filter(x=> regex.test(x));
console.log(s);
JS regex engine does not support POSIX character classes like [:alnum:]. You may use [A-Za-z0-9] instead, but only to match ASCII letters and digits.
Your current regex matches the whole string that contains allowed chars, and it cannot be used to return the chars that are not matched with [^a-zA-Z0-9_.&\s-].
You may remove the unwanted chars with
var s = 'this contains invalid chars like ##';
var res = s.replace(/[^\w\s.&-]+/g, '');
var notallowedchars = s.match(/[^\w\s.&-]+/g);
console.log(res);
console.log(notallowedchars);
The /[^\w\s.&-]+/g pattern matches multiple occurrences (due to /g) of any one or more (due to +) chars other than word chars (digits, letters, _, matched with \w), whitespace (\s), ., & and -.
To match all characters that is not alphanumeric, or one of -_.& move ^ inside group []
var str = 'asd.=!_#$%^&*()564';
console.log(
str.match(/[^a-z0-9\-_.&\s]/gi),
str.replace(/[^a-z0-9\-_.&\s]/gi, '')
);

javascript regex to check if first and last character are similar?

Is there any simple way to check if first and last character of a string are the same or not, only with regex?
I know you can check with charAt
var firstChar = str.charAt(0);
var lastChar = str.charAt(length-1);
console.log(firstChar===lastChar):
I'm not asking for this : Regular Expression to match first and last character
You can use regex with capturing group and its backreference to assert both starting and ending characters are same by capturing the first caharacter. To test the regex match use RegExp#test method.
var regex = /^(.).*\1$/;
console.log(
regex.test('abcdsa')
)
console.log(
regex.test('abcdsaasaw')
)
Regex explanation here :
^ asserts position at start of the string
1st Capturing Group (.)
.* matches any character (except newline) - between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\1 matches the same text as most recently matched by the 1st capturing group
$ asserts position at the end of the string
The . doesn't include newline character, in order include newline update the regex.
var regex = /^([\s\S])[\s\S]*\1$/;
console.log(
regex.test(`abcd
sa`)
)
console.log(
regex.test(`ab
c
dsaasaw`)
)
Refer : How to use JavaScript regex over multiple lines?
Regex explanation here :
[.....] - Match a single character present
\s - matches any whitespace character (equal to [\r\n\t\f\v ])
\S - matches any non-whitespace character (equal to [^\r\n\t\f ])
finally [\s\S] is matches any character.
You can try it
const rg = /^([\w\W]+)[\w\W]*\1$/;
console.log(
rg.test(`abcda`)
)
console.log(
rg.test(`aebcdae`)
)
console.log(
rg.test(`aebcdac`)
)
var rg = /^([a|b])([a|b]+)\1$|^[a|b]$/;
console.log(rg.test('aabbaa'))
console.log(rg.test('a'))
console.log(rg.test('b'))
console.log(rg.test('bab'))
console.log(rg.test('baba'))
This will make sure that characters are none other than a and b which have the same start and end.
It will also match single characters because they too start and end with same character.

Javascript reg exp not right

Here is a string str = '.js("aaa").js("bbb").js("ccc")', I want to write a regular expression to return an Array like this:
[aaa, bbb, ccc];
My regular expression is:
var jsReg = /.js\(['"](.*)['"]\)/g;
var jsAssets = [];
var js;
while ((js = jsReg.exec(find)) !== null) {
jsAssets.push(js[1]);
}
But the jsAssets result is
[""aaa").js("bbb").js("ccc""]
What's wrong with this regular expression?
Use the lazy version of .*:
/\.js\(['"](.*?)['"]\)/g
^
And it would be better if you escape the first dot.
This will match the least number of characters until the next quote.
jsfiddle demo
If you want to allow escaped quotes, use something like this:
/\.js\(['"]((?:\\['"]|[^"])+)['"]\)/g
regex101 demo
I believe it can be done in one-liner with replace and match method calls:
var str = '.js("aaa").js("bbb").js("ccc")';
str.replace(/[^(]*\("([^"]*)"\)[^(]*/g, '$1,').match(/[^,]+/g);
//=> ["aaa", "bbb", "ccc"]
The problem is that you are using .*. That will match any character. You'll have to be a bit more specific with what you are trying to capture.
If it will only ever be word characters you could use \w which matches any word character. This includes [a-zA-Z0-9_]: uppercase, lowercase, numbers and an underscore.
So your regex would look something like this :
var jsReg = /js\(['"](\w*)['"]\)/g;
In
/.js\(['"](.*)['"]\)/g
matches as much as possible, and does not capture group 1, so it matches
"aaa").js("bbb").js("ccc"
but given your example input.
Try
/\.js\(('(?:[^\\']|\\.)*'|"(?:[\\"]|\\.)*"))\)/
To break this down,
\. matches a literal dot
\.js\( matches the literal string ".js("
( starts to capture the string.
[^\\']|\\. matches a character other than quote or backslash or an escaped non-line terminator.
(?:[\\']|\\.)* matches the body of a string
'(?:[\\']|\\.)*' matches a single quoted string
(...|...) captures a single quoted or double quoted string
)\) closes the capturing group and matches a literal close parenthesis
The second major problem is your loop.
You're doing a global match repeatedly which makes no sense.
Get rid of the g modifier, and then things should work better.
Try this one - http://jsfiddle.net/UDYAq/
var str = new String('.js("aaa").js("bbb").js("ccc")');
var regex = /\.js\(\"(.*?)\"\){1,}/gi;
var result = [];
result = str.match (regex);
for (i in result) {
result[i] = result[i].match(/\"(.*?)\"/i)[1];
}
console.log (result);
To be sure that matched characters are surrounded by the same quotes:
/\.js\((['"])(.*?)\1\)/g

regex string replace

I am trying to do a basic string replace using a regex expression, but the answers I have found do not seem to help - they are directly answering each persons unique requirement with little or no explanation.
I am using str = str.replace(/[^a-z0-9+]/g, ''); at the moment. But what I would like to do is allow all alphanumeric characters (a-z and 0-9) and also the '-' character.
Could you please answer this and explain how you concatenate expressions.
This should work :
str = str.replace(/[^a-z0-9-]/g, '');
Everything between the indicates what your are looking for
/ is here to delimit your pattern so you have one to start and one to end
[] indicates the pattern your are looking for on one specific character
^ indicates that you want every character NOT corresponding to what follows
a-z matches any character between 'a' and 'z' included
0-9 matches any digit between '0' and '9' included (meaning any digit)
- the '-' character
g at the end is a special parameter saying that you do not want you regex to stop on the first character matching your pattern but to continue on the whole string
Then your expression is delimited by / before and after.
So here you say "every character not being a letter, a digit or a '-' will be removed from the string".
Just change + to -:
str = str.replace(/[^a-z0-9-]/g, "");
You can read it as:
[^ ]: match NOT from the set
[^a-z0-9-]: match if not a-z, 0-9 or -
/ /g: do global match
More information:
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions
Your character class (the part in the square brackets) is saying that you want to match anything except 0-9 and a-z and +. You aren't explicit about how many a-z or 0-9 you want to match, but I assume the + means you want to replace strings of at least one alphanumeric character. It should read instead:
str = str.replace(/[^-a-z0-9]+/g, "");
Also, if you need to match upper-case letters along with lower case, you should use:
str = str.replace(/[^-a-zA-Z0-9]+/g, "");
str = str.replace(/\W/g, "");
This will be a shorter form
We can use /[a-zA-Z]/g to select small letter and caps letter sting in the word or sentence and replace.
var str = 'MM-DD-yyyy'
var modifiedStr = str.replace(/[a-zA-Z]/g, '_')
console.log(modifiedStr)

regex match text in between

I get strings like:
"some text here /word/ asdhd"
"some other likehere/word1/hahas"
"some other likehere/dhsad huasdhuas huadssad/h ah as/"
What I need is to get the string between the two slashes, 'word', 'word1', 'dhsad huasdhuas huadssad' and 'h ah as'.
What is a regex for that?
Edit in case you have more than one of those words and want to iterate through them.
*Edit again since question was changed.*
var myregexp = /\/(.+?)(?=\/)/g;
var match = myregexp.exec(subject);
while (match != null) {
// matched text: match[1]
match = myregexp.exec(subject);
}
Explanation :
// \/(.+?)(?=\/)
//
// Match the character “/” literally «\/»
// Match the regular expression below and capture its match into backreference number 1 «(.+?)»
// Match any single character that is not a line break character «.+?»
// Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»
// Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=\/)»
// Match the character “/” literally «\/»
var string = "some other likehere/dhsad huasdhuas huadssad/h ah as/";
var matches = string.match(/[/](.*)[/]/)[1];
That should do it.
EDIT revised to match new criteria.
\/[a-zA-Z0-9]+\/
\/ matches slashes
[a-zA-Z0-9] matches any letters uppercase or lower, and any numbers
+ means one or more
"some text here /word/ asdhd".match(/\/(.+)\//)
If you want to match more than one occurence in the same string, you need to use exec. See #FailedDev's answer.

Categories