javascript regex ending string with values in array - javascript

I've to check if my string value is ending with ".com" or ".de"
I've put this values inside array:
var valuesEnd = [".com", ".de"]
My value to compare is taken from form. Also it has to check for # sign, it must have.

Use RegExp#test.
var str = ['abc.de', 'wok.pl', 'qwdok.com'];
console.log(str.map(v => /\w+\.(de|com)$/g.test(v) ? v + ' is valid' : v + ' is invalid'));

You can use a regular expression like this:
var str = prompt("Email: ");
if(/\.(?:com|de)$/.test(str))
alert("'" + str + "' is valid");
else
alert("'" + str + "' is not valid");

I've created a jQuery plugin for you:
(function($) {
// the string object (NOTE: it can be extended)
$.string = {};
// "create" a new string
$.string.new = function(string) {
return string;
};
// test a string for a regex match
$.string.test = function(string, regex) {
return regex.test(string);
};
// join three strings together
$.string.join = function(a, b, c) {
return a + b + c;
};
// log a string to the console
$.string.log = function(string) {
console.log(string);
};
})(jQuery);
Then you would use the plugin like this:
// for test purposes we'll be using: "example#example.com"
var email = $.string.new("example#example.com");
// check to see if the email is valid or not
if($.string.test(email, /\#.*?\.(?:com|de)$/)) {
// let us know that the email is valid
$.string.log($.string.join("'", email, "' is a valid email."));
}
// if this block runs the email is invalid
else {
// let us know that this is an invalid email
$.string.log($.string.join("'", email, "' is not a valid email."));
}

Related

Using Javascript, .test and RegEx to evaluate a URL for /?s=

I want to test the URL http://example.com in a browser window for an empty search string, i.e http://example.com/search/?s=, but not match anything like /search/?s=withsearchterms that has any search terms after the /search/?s=, and then use an if statement and .addClass to display a div that warns that no search terms were entered.
I'm trying to use Javascript and g.test like below; the RegEx pattern is valid, according to several RegEx testers. But no luck:
var href = window.location.href;
var contains = /[\/?s=]+/g.test(href);
if (contains) {
$("#no-search-terms").addClass("display-block");
}
Is my RegEx wrong? Is my use of test wrong?
Edit 11/29/2020
This work, thanks to Heo:
var search = window.location.href;
var regex = /(?<=\/\?s=).*$/
var result=regex.exec( search )
if (result && result[0]=='') {
alert("The search terms are empty.");
} else {
alert("The search terms are not empty or no matched.");
}
But miknik's answer is much simpler with no need for regex. Works on Chrome 87, Firefox 83 and Safari 14:
const queries = new URLSearchParams(window.location.search)
if (queries.has("s") && queries.get("s").length == 0){
alert("The search terms are empty.");
}
You can test if end of string contains /?s=:
var url1 = 'https://example.com/?s=';
var url2 = 'https://example.com/?s=withsearchterms';
var regex = /\/\?s=$/;
console.log(url1 + ' ==> ' + regex.test(url1));
console.log(url2 + ' ==> ' + regex.test(url2));
Output:
https://example.com/?s= ==> true
https://example.com/?s=withsearchterms ==> false
Explanation:
\/\?s= - expect /?s=
$ - trailing $ anchors the regex at the end, e.g. preceding text must occur at the end
thus, the test returns true if the url has no search term (you can reverse your if test)
No need for regex here, something like this should work fine in modern browsers:
const queries = new URLSearchParams(window.location.search)
if (queries.has("s") && queries.get("s").length == 0){
// do stuff
}
Another alternative that (mostly) avoids regular expressions:
function isEmptySearch(urlString) {
const url = new URL(urlString);
const urlParams = url.search.replace(/^\?/, '').split('&').reduce( (acc, cur) => {
const param = cur.split('=');
acc[param[0]] = param[1];
return acc;
}, {});
return !urlParams.s;
}
const testUrls = [
"http://example.com/search/",
"http://example.com/search/?s=",
"http://example.com/search/?s=&foo=bar&baz",
"http://example.com/search/?s=hello&foo=bar&baz"
];
testUrls.forEach( url => console.log(`${url}: empty search = ${isEmptySearch(url)}`) );
I think I prefer the regex option presented earlier by Peter Thoeny as it's less verbose, but this version might be of interest.
If You want to use REGEX, you could use exec() instead of test() because the test function isn't good at the case.
Try this:
//URL-input
var href1 = 'http://example.com/?s='
var href2 = 'http://example.com/?s=xx'
var href3 = 'http://example.com/'
function alertsSearchString( href ){
var regex = /(?<=\/\?s=).*$/
var Container= regex.exec( href )
if ( Container!=null && Container[0]=='' )
alert( 'The search string is an empty string!' )
else if (Container!=null)
alert( 'The search string: ' + Container[0] )
else
alert( "The Container is "
+ Container
+", because input URL isn't matched the \nREGEX : "
+ regex.toString() )
}
//alerts-output
alertsSearchString( href1 )
alertsSearchString( href2 )
alertsSearchString( href3 )
Output:
First Alert : The search string is an empty string!
SecondAlert : The search string: xx
Third Alert : The Container is null because input URL isn't matched the
REGEX : /(?<=\/\?s=).*$/
Detail:
Regex expression: (?<=\/\?s=).*$
(?<=\/\?s=) use lookbehind to check and skip /?s=.
.* match zero to more characters after /?s=.
$ preceding text must occur at the end.
See regex-demo
The source below is an edited from your example Edit 11/22/2020 using exec()
var search = 'http://example.com/search/?s='
var regex = /(?<=\/\?s=).*$/
var result=regex.exec( search )
if (result && result[0]=='') {
alert("The search terms are empty.");
} else {
alert("The search terms are not empty or no matched.");
}
Forget regex, nodejs URL is your friend. https://nodejs.org/dist/latest-v14.x/docs/api/url.html#url_new_url_input_base
for legacy nodejs versions you can use url.parse and querystring.parse
const { URL } = require('url');
const url1 = new URL('https://example.com/?s=');
const url2 = new URL('https://example.com/?s=withsearchterms');
function hasEmptyQuery(u) {
return [...u.searchParams]
.some(([key, value]) => value.length === 0);
}
console.log(hasEmptyQuery(url1));
// true
console.log(hasEmptyQuery(url2));
// false

How to find name from string using Regex in NodeJs

Here is my code , i have written separate function for regex to extract name pattern, passing Regex Pattern with two strings to the function, function matches either one pattern from two input string or it will return 'No_Value'.
function getName(narration_1, narration_2, regex) {
try {
// regex = JSON.parse(regex);
regex = regex.find((item) => { console.log("Item", item); return (new RegExp(item, 'ig').test(narration_1) === true || new RegExp(item, 'ig').test(narration_2) === true)});
console.log("Regex", regex);
let narration = (!!regex) ? (new RegExp(regex, 'ig').test(narration_1) ? narration_1 : narration_2) : null;
let name = (!!narration && narration.match(regex)) ? (!narration.match(regex)[1] ? 'NO_VALUE' : narration.match(regex)[1].trim()) : 'NO_VALUE';
console.log(name);
return name;
} catch(e) {
console.log("Err", e);
// throw new Error(e);
}
}
let string1 ="OPERATION"
let string2 = "退回自動轉賬 WRITE SOMEOPERATIONS TO MR . MANOJ-THOMAS"
let regex = ["MR (.*?) (?:[a-zA-Z]+[0-9]|[0-9]+[a-zA-Z])"];
getName(string1, string2, regex);
I want to extract name from above string 2 MANOJ-THOMAS however the name appears it can also need to match "Mr.","MR .",MR.","MR. ".
I think you can do it this way:
function getName(narration_1, narration_2, regex) {
let name = 'NO_VALUE';
let narration = narration_1.match(regex) || narration_2.match(regex);
if (narration) { // if any match was found in either narration_1 or _2
name = narration[1]; // match method filled this array
console.log("name found: " + name);
}
return name;
}
let regex = new RegExp(".*mr\\s?\\.\\s?(.+)", "i");
let narration_1 = "退回自動轉賬 WRITE SOMEOPERATIONS TO MR . MANOJ-THOMAS";
let narration_2 = "OPERATION";
getName(narration_1, narration_2, regex);
Note that this assumes that the name always is at the end of the string. If that is not the case you will have to extend the regular expression to exclude whatever comes after.

Convert String in the Parenthesis in the URL To Query Parameters: Javascript

I want to convert the string in {} in search URL to query parameters which would help users capture search terms in web analytics tools.
Here's what I am trying to do, Let's say
Search URL is:
example.com/search/newyork-gyms?dev=desktop&id=1220391131
User Input will be:
var search_url_format = '/search/{city}-{service}
Output URL:
example.com/search?city=newyork&service=gyms&dev=desktop&id=1220391131
The problem is when is use the regex {(.*)} it captures the whole string {city}-{service}.
But I what I want is [{city},{service}].
The URL format can also be like
search/{city}/{service}/
search/{city}_{service}/
What I have tried is for a single variable.
It returns correct output.
Eg: URL:/search/newyork
User Input: /search/{city}
Output: /search/newyork?city=newyork
URL: /search-germany
User Input: /search-{country}
Output: /search-germany?country=germany
var search_url_format = '/search/{city}' //User Enters any variable in brackets
var urloutput = '/search/newyork' //Demo URL
//Log output
console.log(URL2Query(search_url_format)) //Output: '/search/newyork?city=newyork'
function URL2Query(url) {
var variableReg = new RegExp(/{(.*)}/)
var string_url = variableReg.exec(url)
var variable1 = string_url[0]
//Capture the variable
var reg = new RegExp(url.replace(variable1, '([^\?|\/|&]+)'))
var search_string = reg.exec(urloutput)[1]
if (location.search.length > 0) // if no query parameters
{
return urloutput + "?" + string_url[1] + "=" + search_string
} else {
return urloutput + "&" + string_url[1] + "=" + search_string
}
}
You are missing two things:
parenthesis to match groups and you use .* which includes "{" sign.
So can use match instead of exec like this:
var search_url_format = '/search/{city}-{service}' //User Enters any
var variableReg = new RegExp(/({\w+})/g)
var string_url = url.match(variableReg); // [{city}, {service}]
You can probably assume your "variable" will be alphanumeric instead of any character. With this assumption "{", "-", "_" etc will be punctuation.
so your grouping regexp could be /({\w+})/g.
//example
const r = /({\w+})/g;
let variable;
const url = '/search/{city}-{service}';
while ((variable = r.exec(url)) !== null) {
let msg = 'Found ' + variable[0] + '. ';
msg += 'Next match starts at ' + r.lastIndex;
console.log(msg);
}

Search Array for strings and return matches^

I have an array with names of employees such as.
var names = ['Jordan,Michael','Davis,Jordan','Franco,James','Rogen,Seth','Griffin,Peter','James,Tim',..]
I would like to add a feature to my webpage to allow the user to type in the name they are looking for and be able to see everyone with that name. So if the user typed in Jordan. Both Jordan,Michael and Davis,Jordan would return.
Is there a way that I can do this with javascript/jquery?
Use Array.prototype.filter
var search = 'Jordan';
var names = ['Jordan,Michael','Davis,Jordan','Franco,James','Rogen,Seth','Griffin,Peter','James,Tim']
var results = names.filter(name => name.indexOf(search) > -1);
console.log(results);
For case in-sensitive match, you need to use regex.
The following code snippet assumes that there are only alpha-numeric characters in both needle and haystack.The special characters can be removed by using a simple replace, str = str.replace(/[^a-zA-Z0-9]/g, '');
Note: To allow special characters, they need to be escaped.
var names = ['Jordan,Michael','Davis,Jordan','Franco,James','Rogen,Seth','Griffin,Peter','James,Tim']
var search = 'jorDan' // cAsE-InsEnsItIvE
regex = new RegExp(search, 'i');
var results = names.filter(name => regex.test(name));
console.log(results);
document.body.innerHTML = '<pre>' + JSON.stringify(results, 0, 4) + '</pre>';
Try having an array of objects like this:
var names = [
{firstName:'Jordan', lastName:'Michael'},
{firstName:'Davis', lastName:'Jordan'},
]
var searchedName = "Jordan";
var result = names.filter(function( searchedName) {
return names.firstName == searchedName || names.lastName == searchedName;
});
This is a fuzzy search field, I couldn't think of any names so this one has three Tims to illustrate the point.
It uses a Regular expression to match the letters currently being typed into the input field.
var names = [
'Jordan,Michael',
'Davis,Jordan',
'Franco,James',
'Rogen,Seth',
'Griffin,Peter',
'James,Tim',
'Burton,Tim',
'Allen,Tim'
];
var
input = document.querySelector('#input'),
results = document.querySelector('#results');
input.addEventListener('keyup', function(e) {
filterNames( this.value );
});
// init the filter;
filterNames('');
// helper to filter the names array by a value
function filterNames( value ){
results.innerHTML = names.filter(function(name) {
return name.match(new RegExp( value.split('').join('.*'), 'ig'));
}).reduce(function( str, name) {
return str + '<li>' + name + '</li>';
}, '');
}
<input type="text" id="input">
<ul id="results"></ul>

find text in string and replace it

I have a variable which contains a string expression. This expression have the pattern:
propery_expression operator value
proeprty_expression can look like:
World
World/Name
City/Name
I want to find text after /, and If it exists, and replace with custom text. How can I do this?
With a regex, for example this one :
yourString.replace(/\/\S+/, '/the new stuff...');
In the console :
> var cityName = 'Djakarta';
> var line = 'World/Name Something SomethingElse';
> line.replace(/\/\S+/, '/' + cityName);
"World/Djakarta Something SomethingElse"
You can use this to do complex search and replace operations. Details on Mozilla's documentation
You could try this
var the_string = "City/Name";
var word = "New";
var result = the_string.substring(0, the_string.lastIndexOf('/') + 1);
alert(result + word);
You can try this:
var str = 'World';
alert(rep(str));
function rep(str)
{
if(str.indexOf('/')>-1)//present
{
alert(str.substring(str.lastIndexOf('/') + 1,str.length));
var res = str.replace(str.substring(str.lastIndexOf('/') + 1,str.length),'custom_word');
return res;
}
else{
alert(' / not present');
return str;
}
}
DEMO
Note: If text present after / then it replace it with "custom_word".
In addition to Mathias's answer, you could use RegEx together with a function, like so:
var myString;
.
.
.
myString.replace(/\/(\S+)/g, function (found, value) {
// found == "City/NewYork"
// value == "NewYork"
return found + "Altered";
}
This, for example, will change every "x/y" with "x/yAltered"

Categories

Resources