How to match a fixed string with digits with javascript? - javascript

The String is - Success0 or Success7 or any digit.I tried with -
console.log(str.match("Success"+/\d/));
But it is logging null. Any help?

Your regex in .match() isnt right.
Do:
var str = "Success123";
alert(str.match(/^Success\d+$/)); // returns the string if it is a match, otherwise null
Note that if you are just testing the string if it has Success at the begining, you should be using .test(). .match() takes a toll on the browser as compared to .test().
var str = "Success123";
alert(/^Success\d+$/.test(str)); // returns true/false
Regex /^Success\d+$/ explained here.
Readup:
.test() | MDN
.match() | MDN

Try this instead:
str.match(/Success\d+/)

Assuming you are having numbers and it's the whole string :
str.match(/^Success\d+$/)
Ir you want to build up your regex :
var r= new RegExp("^Success"+'\\d+$')
console.log(r.test('Success232'));

Related

Javascript - When a string does not Match itself [duplicate]

This question already has answers here:
Is there a RegExp.escape function in JavaScript?
(18 answers)
Closed 3 years ago.
I have this Example 1:
myString = 'cdn.google.com/something.png';
console.log(myString.match(myString));
Everything works just fine, but when it comes to Example 2:
myString = 'cdn.google.com/something.png?231564';
console.log(myString.match(myString));
It returns the value of 'null'. I don't know what happened anymore.. I searched for the keywords 'a string does not Match itself' and found nothing. Can somebody help me? Thank you.
The String#match method would treat the argument as a regex(by parsing if not), where . and ? has special meaning.
. matches any character (except for line terminators)
? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed
So . wouldn't cause any problem since . can be used to match any character except line but ? would since it's using to match zero or one-time occurrence of any character.
For eg: .png?23 => matches .png23 or .pn23
From MDN docs :
If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).
It's better to use String#indexOf instead which returns the index in the string if found or returns -1 if not found.
console.log(myString.indexOf(myString) > -1);
match in Javascript compares a String against a RegEx. Luckily in your first example it works.
I guess you are looking for a method like localCompare.
Hope this helps!
match() search the string using a regular expression pattern.
So
var s = "My String";
s.match(/Regex Here/);
will try to match s for given regular expression .
In your example:-
myString = 'cdn.google.com/something.png'; // It will be treated as regex
console.log(myString.match(myString));
myString = 'cdn.google.com/something.png?231564'; // It will be treated as regex , result differ because of ?
console.log(myString.match(myString));
You can escape the argument to match, however if you do that you could just use == to compare the strings. This post contains a regex string escape function:
How to escape regular expression in javascript?
RegExp.quote = function(str) {
return (str+'').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
};
It can be used like this:
myString = 'cdn.google.com/something.png?231564';
console.log(myString.match(RegExp.quote
(myString)));
If you want to match any number after the question mark, you could do it like this:
myString = 'cdn.google.com/something.png?';
console.log((myString+"18193819").match(RegExp.quote
(myString) + '\\d+'));

How to regex test a string for a pattern while excluding certain characters?

I'm getting nowhere with this...
I need to test a string if it contains %2 and at the same time does not contain /. I can't get it to work using regex. Here is what I have:
var re = new RegExp(/.([^\/]|(%2))*/g);
var s = "somePotentially%2encodedStringwhichMayContain/slashes";
console.log(re.test(s)) // true
Question:
How can I write a regex that checks a string if it contains %2 while not containing any / slashes?
While the link referred to by Sebastian S. is correct, there's an easier way to do this as you only need to check if a single character is not in the string.
/^[^\/]*%2[^\/]*$/
EDIT: Too late... Oh well :P
Try the following:
^(?!.*/).*%2
either use inverse matching as shown here: Regular expression to match a line that doesn't contain a word?
or use indexOf(char) in an if statement. indexOf returns the position of a string or char in a string. If not found, it will return -1:
var s = "test/";
if(s.indexOf("/")!=-1){
//contains "/"
}else {
//doesn't contain "/"
}

Extracting numbers from a string using regular expressions

I am clueless about regular expressions, but I know that they're the right tool for what I'm trying to do here: I'm trying to extract a numerical value from a string like this one:
approval=not requested^assignment_group=12345678901234567890123456789012^category=Test^contact_type=phone^
Ideally, I'd extract the following from it: 12345678901234567890123456789012 None of the regexes I've tried have worked. How can I get the value I want from this string?
This will get all the numbers:
var myValue = /\d+/.exec(myString)
mystr.match(/assignment_group=([^\^]+)/)[1]; //=> "12345678901234567890123456789012"
This will find everything from the end of "assignment_group=" up to the next caret ^ symbol.
Try something like this:
/\^assignment_group=(\d*)\^/
This will get the number for assignment_group.
var str = 'approval=not requested^assignment_group=12345678901234567890123456789012^category=Test^contact_type=phone^',
regex = /\^assignment_group=(\d*)\^/,
matches = str.match(regex),
id = matches !== null ? matches[1] : '';
console.log(id);
If there is no chance of there being numbers anywhere but when you need them, you could just do:
\d+
the \d matches digits, and the + says "match any number of whatever this follows"

Splitting and returning part of a string

I have two strings such as:
sometext~somemoretext~extratext
and
sometext~otherextratext
I wish to crop off the last tilde (~) and all text to the right. For instance, the above two strings would result in:
sometext~somemoretext
and
sometext
Thanks
lastIndexOf(char) returns the position of the last found occurrence of a specified value in a string
substring(from, to) extracts the characters from a string, between two specified indices, and returns the new sub string
For instance:
var txt = 'sometext~somemoretext~extratext';
txt = txt.substring(0, txt.lastIndexOf('~'));
DEMO
I strongly suggest you to read the doc on the Javascript String Object
return theString.replace(/~[^~]*$/, '');
You can do this using a regular expression with the .replace() DOCs method.
var str = 'sometext~somemoretext~extratext';
str = str.replace(/~[\w\s]+$/, '');
Here is a jsFiddle of the above code for you to run: http://jsfiddle.net/NELFB/
you can use substr to split the string, then rebuild them for what ever you need
var someString = "sometext~otherextratext";
someString = someString.split('~');
this will give you an array, which you can use like someString[0];
use .replace('~', '') if you need to further remove the ones at the end of strings
this should do it
function removeExtra(input){
return input.substr(0,input.lastIndexOf('~'))
}

one line match in JS regex

What is the JavaScript equivalent of this .NET code?
var b = Regex.IsMatch(txt, pattern);
Here are the useful functions for working with regexes.
exec A RegExp method that executes a search for a match in a string. It returns an array of information.
test A RegExp method that tests for a match in a string. It returns true or false.
match A String method that executes a search for a match in a string. It returns an array of information or null on a mismatch.
search A String method that tests for a match in a string. It returns the index of the match, or -1 if the search fails.
replace A String method that executes a search for a match in a string, and replaces the matched substring with a replacement substring.
split A String method that uses a regular expression or a fixed string to break a string into an array of substrings.
Source: MDC
So to answer your question, as the others have said:
/pattern/.test(txt)
Or, if it is more convenient for your particular use, this is equivalent:
txt.search(/pattern/) !== -1
var b = /pattern/.test(txt);
/pattern/.test(txt);
E.g.:
/foo \w+/.test("foo bar");
It returns true for a match, just like IsMatch.
var regex = new RegExp(pattern);
var b = regex.test(text);
You can also use var b = /pattern/.test(text) but then you can't use a variable for the regex pattern.

Categories