convert regex string to regex object in javascript - javascript

I am getting regex string from json object (yes its dynamic and will be always be string) i want to test this with textbox value.
But even if i pass valid input text it does not pass regex condition
code :
var pattern = "/^[A-Za-z\s]+$/";
var str = "Some Name";
pattern = new RegExp(pattern);
if(pattern.test(str))
{
alert('valid');
}
else
{
alert('invalid');
}
Fiddle :- http://jsfiddle.net/wn9scv3m/

Two problems:
You need to escape the backslash.
You need to remove the forward slashes on the beginning and end of string.
Corrected code:
var pattern = "^[A-Za-z\\s]+$";
var str = "Some Name";
pattern = new RegExp(pattern);
if(pattern.test(str))
{
alert('valid');
}
else
{
alert('invalid');
}
http://jsfiddle.net/wn9scv3m/3/

Use regex-parser:
const parseRegex = require("regex-parser")
parseRegex("/^hi$/g")
// => /^hi$/g

This should work for you (jsfiddle: http://jsfiddle.net/wn9scv3m/9/):
var pattern = /^[(\w)|(\s)]+$/; // using / regex constructor...
var altPattern = "^[(\w)|(\s)]+$"; // using quotes and new RegEx() syntax...
var regex = new RegExp(altPattern);
var str = "Some Name";
if (str.match(pattern) != null && regex.test(str) != null) { // check using both methods
alert('valid');
}
else {
alert('invalid');
}

As far as I can see in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions you are combining two methods to declare RegExp. If you are using the string variant, then don't include the "/" character before and after the expression, example:
var pattern = "^[A-Za-z\s]+$";
pattern = new RegExp(pattern);
If you like the /regexp/ form better, then use it without quotes:
pattern = /^[A-Za-z\s]+$/;

this should work
var str1 = "SomeName"; //true
var str2 = "SomeName123"; //false
function MyRegex(val) {
var pattern = /^[A-Za-z\s]+$/;
var match = pattern.exec(val);
return match !== null && match[0] === val;
}
alert(MyRegex(str1));
alert(MyRegex(str2));

Related

create regexp for username validation

I need some help creating regexp. It's just I don't quite understand how to create a regexp. How do i create a validation for username with some rules like this
only Uppercase, lowercase, underscore(_) and dot(.) are allowed
start with an underscore(_)
I've already tried some regexp from mozilla developer site, but it doesn't seems right
var usernameRegex = new RegExp(/_+[A-Za-z]/);
var usernameRegexFound = usernameRegex.test(username.value);
if (!usernameRegexFound) {
msg = "Invalid Username";
}
I expect some username like so
_username = true
_username1 = false
.username = false
username = false
and also are there any sites for me to understand how to create regexp, because I got some more thing to do with it
function validuser(username) {
var msg = "valid";
var usernameRegex = new RegExp(/_+[A-Za-z]/);
var usernameRegexFound = usernameRegex.test(username);
if (!usernameRegexFound) {
msg = "Invalid Username";
}
return msg;
}
console.log(validuser("_username","Valid?"));
console.log(validuser("_username1","Invalid?"));
console.log(validuser(".username","Invalid?"));
console.log(validuser("username","Invalid?"));
When creating regex, you can help yourself using https://regex101.com/.
That said, here is your regex :
function test(username) {
const regex = new RegExp('^_{1}[A-Za-z\.]*$', 'i');
// Alternative version considering #thomas points
// const regex = new RegExp('^_[A-Za-z._]+$', 'i');
return regex.test(username);
}
console.log(test('test'));
console.log(test('_test'));
console.log(test('_te.s.t'));
console.log(test('_teST'));
console.log(test('Test_'));
console.log(test('^zdq^dz.'));
console.log(test('_teS/T'));
console.log(test('_9901A'));

Manipulate input string while doing a regex search

trying to find every match in a string and process it with a custom function and replace it in the string. When I set text = to the new string though, it never changes, and in the end remains the unchanged.
function submit () {
var searchTerm = document.querySelector('#search-term').value;
var replaceFunction = Function('input', document.querySelector('#function').value);
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
var output = text;
var regex = new RegExp('\d', 'g');
var match, matches = [];
//search for replacements
while ((match = regex.exec(text)) != null) {
var beforeMatch = output.substring(0, match.index);
var afterMatch = output.substring(match.index + match[0].length, text.length);
text = beforeMatch + replaceFunction(match[0]) + afterMatch;
console.log(text);
}
console.log('result', text);
}
function replaceFunction (input) {
return input * 2;
}
You can achieve same result with far less code using replace() and its function's callback that takes match as parameter.
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
text = text.replace(/\d+/g, function(match){
return parseInt(match) * 2;
})
console.log(text)
First of all, you need to use \\ for escape sequence if you are using RegExp constructor. Alternatively you can use the RegExp literal as shown below. Moreover you are using only \d which is going to match a single digit. Instead you should be using \d+ that will match the complete number.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
When using the constructor function, the normal string escape rules
(preceding special characters with \ when included in a string) are
necessary. For example, the following are equivalent:
var re = /\w+/;
var re = new RegExp('\\w+');
Then you are trying to manipulate the string using a loop. Instead simply use replace function as shown below.
function submit () {
// var searchTerm = document.querySelector('#search-term').value;
// var replaceFunction = Function('input', document.querySelector('#function').value);
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
var output = text;
var regex = new RegExp('\\d+', 'g'); // <<<<<< RegExp constructor
// OR
regex = /\d+/g; // <<<<<<< RegExp literal
var match, matches = [];
console.log(text);
output = text.replace(regex, replaceFunction);
console.log('result', output);
}
function replaceFunction (input) {
return parseInt(input) * 2;
}
submit();
Disclaimer: Using RegExp for manipulating HTML elements and attributes is not a good idea and you may end up in unexpected issues if its not used carefully. Use it at your own risk.

How can I remove a containing [" "] from a string variable if it exists?

I have string variables that can look like this:
var a = '["Email cannot be null or empty."]';
var b = 'test string';
Is there a way I can check if the variables start and end in '["' , ']"' and if so then these be removed so that the variables become:
var a = 'Email cannot be null or empty.';
var b = 'test string';
What I am looking for is a one line solution if it's possible. I am not sure if I could use some regex or index function. Any advice would be much appreciated.
If you know that is a likely scenario, with few deviations:
function unformatString(str) {
try {
str = JSON.parse(str);
if (Object.prototype.toString.call(str) === '[object Array]') {
return str[0];
}
} catch (err) { }
return str;
}
var a = unformatString('["Email cannot be null or empty."]');
var b = unformatString('test string');
In your case, the above solution is probably the better one, but an alternative solution for text replacement is the String.replace() method.
You could fix your strings with:
a = a.replace("[\"", "");
a = a.replace("\"]", "");
This would remove the strings [" and "] from anywhere in the string, whether it is in the front, back, or middle of the string. String.replace() also supports regular expressions, not just strings, so you could write a quick regex in its place if necessary.
if(a.indexOf('["')==0 && a.indexOf('"]')==a.length-2)
{
a = a.replace('[\"', '');
a = a.replace('\"]', '');
}
First I am checking If variables start and end in '["' , ']"'
This code will remove [" at the beginning and "] at the end of a string DEMO
var a = '["Email cannot be null or empty."]';
a = a.replace(/^\[\"/,'').replace(/\"\]$/,'');
alert(a);
Try this:
var a = '["Email cannot be null or empty."]';
a.replace(/[\[\"\]]/g, "")
//output "Email cannot be null or empty."
You can do this with Regular expressions using exec() method.
var cleanInput = function(str) {
var patt = /\["(.*)"]/g;
if( (result = patt.exec(str)) !== null )
return result[1];
else
return str;
},
input1 = '["Dummy string"]',
input2 = '["Another dummy string"]',
// Checking Inputs
input1 = cleanInput(input1),
input2 = cleanInput(input2);
http://jsfiddle.net/Uu8Ht/

truncating a string after and before a word in javascript

How do I truncate a string after or before a pattern?
Say if I have a string "abcdef" I need to truncate everything after "abc" so the output will be:
def
and if i say truncate before "def" the output should be:
abc
Below is the code that I tried
var str1 = "abcdefgh";
var str2 = str1.substr(str1.indexOf("abc"), str1.length);
console.log(str2);
I didn't get the output.
I'm stuck here any help will be much appreciated.
You need to pass length of "abc" as the 2nd argument in substr method
var str1 = "abcdefgh";
var pattern = "abc";
var str2 = str1.substr(str1.indexOf(pattern), pattern.length); <-- check this line
console.log(str2);
However above code might return unexpected results for patterns which are not present in the string.
var str1 = "abcdefgh";
var pattern = "bcd";
var str2 = "";
if(str1.indexOf(pattern)>=0) //if a pattern is not present in the source string indexOf method returns -1
{
//to truncate everything before the pattern
//outputs "efgh"
str2 = str1.substr(str1.indexOf(pattern)+pattern.length, str1.length);
console.log("str2: "+str2);
// if you want to truncate everything after the pattern & pattern itself
//outputs "a"
str3 = str1.substr(0, str1.indexOf(pattern));
console.log("str3: "+str3);
}
var str = "sometextabcdefine";
var pattern = "abc";
var truncateBefore = function (str, pattern) {
return str.slice(str.indexOf(pattern) + pattern.length);
};
var truncateAfter = function (str, pattern) {
return str.slice(0, str.indexOf(pattern));
}
console.log(truncateBefore(str, pattern)); // "define"
console.log(truncateAfter(str, pattern)); // "sometext"
Please see the below code:
var str1 = "abcdefgh";
var str2 = str1.substr(str1.indexOf("abc")+3, str1.length);
alert(str2);
You were correct but one thing you missed is doing +3 in the indexOf.
the indexOf("abc") would return 0 which in turn will give you thw whole string again.
Or check out this fiddle link:
Working Fiddle
How about something like this:
function truncateAfter(original, pattern) {
return original.substring(0, original.indexOf(pattern) + pattern.length);
}
What this does is find the first index of the pattern you're looking for, and return a substring of the original string that starts at the beginning and ends after the first instance of the pattern.
Example Usage:
truncateAfter('dabcdefghi', 'abc');
>> 'dabc'
If instead you want to truncate the output before and after the pattern you're looking for, would just checking if the pattern is in the string and then using the pattern as the output be what you're looking for?
function truncate(original, pattern) {
if (original.indexOf(pattern) != -1) {
return pattern;
}
}
Example Usage:
truncate('dabcdefghi', 'abc');
>> 'abc'

Detect presence of a specific pattern in Javascript String

How can i do to search if a Javascript String contains the following pattern :
"#aRandomString.temp"
I would like to know if the String contains # character and then any String and then ".temp" string.
Thanks
This one liner should do the job using regex#test(Strng):
var s = 'foo bar #aRandomString.temp baz';
found = /#.*?\.temp/i.test(s); // true
Use indexOf to find a string within a string.
var string = "#aRandomString.temp";
var apos = string.indexOf("#");
var dtemp = string.indexOf(".temp", apos); // apos as offset, invalid: ".temp #"
if (apos !== -1 && dtemp !== -1) {
var aRandomString = string.substr(apos + 1, dtemp - apos);
console.log(aRandomString); // "aRandomString"
}
You can try this
var str = "#something.temp";
if (str.match("^#") && str.match(".temp$")) {
}
demo
You can use the match function.
match expects the regular expression.
function myFunction()
{
var str="#someting.temp";
var n=str.test(/#[a-zA-Z]+\.temp/g);
}
Here is a demo: http://jsbin.com/IBACAB/1

Categories