I am not very familiar with regex. I was trying to test if a string ends with another string. The code below returns null when I was expecting true. What's wrong with the code?
var id = "John";
var exists ="blahJohn".match(/id$/);
alert(exists);
Well, with this approach, you would need to use the RegExp constructor, to build a regular expression using your id variable:
var id = "John";
var exists = new RegExp(id+"$").test("blahJohn");
alert(exists);
But there are plenty ways to achieve that, for example, you can take the last id.length characters of the string, and compare it with id:
var id = "John";
var exist = "blahJohn".slice(-id.length) == id; // true
You would need to use a RegExp() object to do that, not a literal:
var id = "John",
reg = new RegExp(id+"$");
alert( reg.test("blahJon") );
That is, if you do not know the value you are testing for ahead of runtime. Otherwise you could do:
alert( /John$/.test("blahJohn") );
Try this -
var reg = "/" + id + "$/";
var exists ="blahJohn".match(reg);
The nicer way to do this is to use RegExp.test:
(new RegExp(id + '$')).test('blahJohn'); // true
(new RegExp(id + '$')).test('blahJohnblah'); // false
Even nicer would be to build a simple function like this:
function strEndsWith (haystack, needle) {
return needle === haystack.substr(0 - needle.length);
}
strEndsWith('blahJohn', id); // true
strEndsWith('blahJohnblah', id); // false
var id = new RegExp("John");
var exists ="blahJohn".match(id);
alert(exists);
try this
I like #lonesomeday 's solution, but Im fan of extending the String.prototype in these scenarios. Here's my adaptation of his solution
String.prototype.endsWith = function (needle) {
return needle === this.substr(0 - needle.length);
}
So can be checked with
if(myStr.endsWith("test")) // Do awesome things here.
Tasty...
var id = "John";
(new RegExp(`${id}$`)).test('blahJohn'); // true
(new RegExp(`${id}$`)).test('blahJohna'); // false
`${id}$` is a JavaScript Template strings which will be compiled to 'John$'.
The $ after John in RegExp stands for end of string so the tested string must not have anything after id value (i.e. John) in order to pass the test.
new RegExp(`${id}$`) - will compile it to /John$/ (so if id shouldn't be dynamic you can use just /John$/ instead of new RegExp(`${id}$`) )
Why using RegExp? Its expensive.
function EndsWith( givenStr, subst )
{
var ln = givenStr.length;
var idx = ln-subst.length;
return ( giventStr.subst(idx)==subst );
}
Much easier and cost-effective, is it?
If you need it for replace function, consider this regExp:
var eventStr = "Hello% World%";
eventStr = eventStr.replace(/[\%]$/, "").replace(/^[\%]/, ""); // replace eds with, and also start with %.
//output: eventStr = "Hello% World";
2022, ECMA 11
Just created this helper function, I find it more useful and clean than modifying the regex and recreating one everytime.
/**
* #param {string} str
* #param {RegExp} search
* #returns {boolean}
*/
function regexEndsWith (str, search, {caseSensitive = true} = {})
{
var source = search.source
if (!source.endsWith('$')) source = source + '$'
var flags = search.flags
if (!caseSensitive && !flags.includes('i')) flags += 'i'
var reg = new RegExp(source, flags)
return reg.test(str)
}
Use it this way:
regexEndsWith('can you Fi nD me?', /fi.*nd me?/, {caseSensitive: false})
Here is a string prototype function that utilizes regex. You can use it to check if any string object ends with a particular string value:
Prototype function:
String.prototype.endsWith = function (endString) {
if(this && this.length) {
result = new RegExp(endString + '$').test(this);
return result;
}
return false;
}
Example Usage:
var s1 = "My String";
s1.endsWith("ring"); // returns true;
s1.endsWith("deez"); //returns false;
Related
i have comma separated string like
var test = 1,3,4,5,6,
i want to remove particular character from this string using java script
can anyone suggests me?
JavaScript strings provide you with replace method which takes as a parameter a string of which the first instance is replaced or a RegEx, which if being global, replaces all instances.
Example:
var str = 'aba';
str.replace('a', ''); // results in 'ba'
str.replace(/a/g, ''); // results in 'b'
If you alert str - you will get back the same original string cause strings are immutable.
You will need to assign it back to the string :
str = str.replace('a', '');
Use replace and if you want to remove multiple occurrence of the character use
replace like this
var test = "1,3,4,5,6,";
var newTest = test.replace(/,/g, '-');
here newTest will became "1-3-4-5-6-"
you can make use of JavaScript replace() Method
var str="Visit Microsoft!";
var n=str.replace("Microsoft","My Blog");
var test = '1,3,4,5,6';
//to remove character
document.write(test.replace(/,/g, ''));
//to remove number
function removeNum(string, val){
var arr = string.split(',');
for(var i in arr){
if(arr[i] == val){
arr.splice(i, 1);
i--;
}
}
return arr.join(',');
}
var str = removeNum(test,3);
document.write(str); // output 1,4,5,6
You can also
var test1 = test.split(',');
delete test1[2];
var test2 = test1.toString();
Have fun :)
you can split the string by comma into an array and then remove the particular element [character or number or even string] from that array. once the element(s) removed, you can join the elements in the array into a string again
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
You can use this function
function removeComma(inputNumber,char='') {
return inputNumber.replace(/,/g, char);
}
Update
function removeComma(inputNumber) {
inputNumber = inputNumber.toString();
return Number(inputNumber.replace(/,/g, ''));
}
I am trying to replace a string with two sets of patterns. For example,
var pattern1 = '12345abcde/'; -> this is dynamic.
var myString = '12345abcde/hd123/godaddy_item'
my end goal is to get the value between two slashes which is hd123
I have
var stringIneed = myString.replace(pattern1, '').replace('godaddy_item','');
The above codes work but I think there is more elegant solution. Can anyone help me out on this? Thanks a lot!
UPDATE:
To be more clear, the pattern is per environement string. For example,
pattern1 could be something like:
https://myproject-development/item on development environment.
and
https://myproject/item on Production
myString could usually be like
https://myproject/item/hd123/godaddy_item
or
https://myproject-development/item/hd123/godaddy_item
and I need to get 'hd123' in my case.
I'd strongly suggest not using regular expressions for this, especially when simple String and Array methods will easily suffice and be far more understandable, such as:
// your question shows you can anticipate the sections you
// don't require, so put both/all of those portions into an
// array:
var unwanted = ['12345abcde', 'godaddy_item'],
// the string you wish to find the segment from:
myString = '12345abcde/hd123/godaddy_item',
// splitting the String into an array by splitting on the '/'
// characters, filtering that array using an arrow function
// in which the section is the current array-element of the
// array over which we're iterating; and here we keep those
// sections which are not found in the unwanted Array (the index
// an element not found in an Array is returned as -1):
desired = myString.split('/').filter(section => unwanted.indexOf(section) === -1);
console.log(desired); // ["hd123"]
Avoiding Arrow functions, for browsers not supporting ES6 (and having removed the code comments):
var unwanted = ['12345abcde', 'godaddy_item'],
myString = '12345abcde/hd123/godaddy_item',
desired = myString.split('/').filter(function (section) {
return unwanted.indexOf(section) === -1;
});
console.log(desired); // ["hd123"]
Or:
// the string to start with and filter:
var myString = '12345abcde/hd123/godaddy_item',
// splitting the string by the '/' characters and keeping those whose
// index is greater than 0 (so 'not the first') and also less than the
// length of the array-1 (since JS arrays are zero-indexed while length
// is 1-based):
wanted = myString.split('/').filter((section, index, array) => index > 0 && index < array.length - 1);
console.log(wanted); // ["hd123"]
JS Fiddle demo
If, however, the requisite string to be found is always the penultimate portion of the supplied string, then we can use Array.prototype.filter() to return only that portion:
var myString = '12345abcde/hd123/godaddy_item',
wanted = myString.split('/').filter((section, index, array) => index === array.length - 2);
console.log(wanted); // ["hd123"]
JS Fiddle demo.
References:
Array.prototype.filter().
Arrow functions.
String.prototype.split().
You can use
.*\/([^\/]+)\/.*$
Regex Demo
JS Demo
var re = /.*\/([^\/]+)\/.*$/g;
var str = '12345abcde/hd123/godaddy_item';
while ((m = re.exec(str)) !== null) {
document.writeln("<pre>" + m[1] + "</br>" + "</pre>");
}
You can easily do something like this:
myString.split('/').slice(-2)[0]
This will return the item directly, in simple most way.
var myString = 'https://myproject/item/hd123/godaddy_item';
console.log(myString.split('/').slice(-2)[0]); // hd123
myString = 'https://myproject-development/item/hd123/godaddy_item';
console.log(myString.split('/').slice(-2)[0]); // hd123
Try using match() as shown below:
var re = /\/(.*)\//;
var str = '12345abcde/hd123/godaddy_item';
var result = str.match(re);
alert(result[1]);
To say that David's answer will "easily suffice and be far more understandable" is a matter of opinion - this regex option (which includes building up the expression from variables) really couldn't be much simpler:
var pathPrefix = '12345abcde/'; //dynamic
var pathToTest = '12345abcde/hd123/godaddy_item';
var pattern = new RegExp(pathPrefix + '(.*?)\/')
var match = pattern.exec(pathToTest);
var result = (match != null && match[1] != null ? '[' + match[1] + ']' : 'no match was found.'); //[hd123]
I've a email as string (let's say "testdrive#gmail.com") and I want to check if email contains character "test" then capitalize that
(ex. testdrive#gmail.com = "TESTdrive#gmail.com", drivetest#gmail.com= "driveTEST#gmail.com"...).
How do I get this in JavaScript?
Thanks!
You can do it with the String.prototype.replace and String.prototype.toUpperCase functions like this:
var original = "testdrive#gmail.com"
var replaceTerm = 'test';
var modified = original.replace(replaceTerm, replaceTerm.toUpperCase());
console.log(modified); //logs TESTdrive#gmail.com
Javascript's replace method is the easiest way to find and replace an exact keyword. The first parameter is the string you are searching for. The second is what you want to replace that string with.
var str = "testdrive#gmail.com";
var x = str.replace('test', 'TEST');
console.log(x); //TESTdrive#gmail.com
function capitalizer() {
var mail = "drivetest#gmail.com";
var srchStr = "test";
var n = mail.search(srchStr);
var capitalized = mail.replace(srchStr,mail.substr(n, srchStr.length).toUpperCase());
document.getElementById("demo").innerHTML = capitalized;
}
I am trying to select just what comes after name= and before the & in :
"/pages/new?name=J&return_url=/page/new"
So far I have..
^name=(.*?).
I am trying to return in this case, just the J, but its dynamic so it could very several characters, letters, or numbers.
The end case situation would be allowing myself to do a replace statement on this dynamic variable found by regex.
/name=([^&]*)/
remove the ^ and end with an &
Example:
var str = "/pages/new?name=J&return_url=/page/new";
var matches = str.match(/name=([^&]*)/);
alert(matches[1]);
The better way is to break all the params down (Example using current address):
function getParams (str) {
var queryString = str || window.location.search || '';
var keyValPairs = [];
var params = {};
queryString = queryString.replace(/.*?\?/,"");
if (queryString.length)
{
keyValPairs = queryString.split('&');
for (pairNum in keyValPairs)
{
var key = keyValPairs[pairNum].split('=')[0];
if (!key.length) continue;
if (typeof params[key] === 'undefined')
params[key] = [];
params[key].push(keyValPairs[pairNum].split('=')[1]);
}
}
return params;
}
var url = "/pages/new?name=L&return_url=/page/new";
var params = getParams(url);
params['name'];
Update
Though still not supported in any version of IE, URLSearchParams provides a native way of retrieving values for other browsers.
The accepted answer includes the hash part if there is a hash right after the params. As #bishoy has in his function, the correct regex would be
/name=([^&#]*)/
Improving on previous answers:
/**
*
* #param {string} name
* #returns {string|null}
*/
function getQueryParam(name) {
var q = window.location.search.match(new RegExp('[?&]' + name + '=([^&#]*)'));
return q && q[1];
}
getQueryParam('a'); // returns '1' on page http://domain.com/page.html?a=1&b=2
here is the full function (tested and fixed for upper/lower case)
function getParameterByName (name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name.toLowerCase() + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search.toLowerCase());
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
The following should work:
\?name=(.*?)&
var myname = str.match(/\?name=([^&]+)&/)[1];
The [1] is because you apparently want the value of the group (the part of the regex in brackets).
var str = "/pages/new?name=reaojr&return_url=/page/new";
var matchobj = str.match(/\?name=([^&]+)&/)[1];
document.writeln(matchobj); // prints 'reaojr'
Here's a single line answer that prevents having to store a variable (if you can't use URLSearchParams because you still support IE)
(document.location.search.match(/[?&]name=([^&]+)/)||[null,null])[1]
By adding in the ||[null,null] and surrounding it in parentheses, you can safely index item 1 in the array without having to check if match came back with results. Of course, you can replace the [null,null] with whatever you'd like as a default.
You can get the same result with simple .split() in javascript.
let value = url.split("name=")[1].split("&")[0];
This might work:
\??(.*=.+)*(&.*=.+)?
Let's say I have a URL:
http://something.com/somethingheretoo
and I want to get what's after the 3rd instance of /?
something like the equivalent of indexOf() which lets me input which instance of the backslash I want.
If you know it starts with http:// or https://, just skip past that part with this one-liner:
var content = aURL.substring(aURL.indexOf('/', 8));
This gives you more flexibility if there are multiple slashes in that segment you want.
let s = 'http://something.com/somethingheretoo';
parts = s.split('/');
parts.splice(0, 2);
return parts.join('/');
Try something like the following function, which will return the index of the nth occurrence of the search string s, or -1 if there are n-1 or fewer matches.
String.prototype.nthIndexOf = function(s, n) {
var i = -1;
while(n-- > 0 && -1 != (i = this.indexOf(s, i+1)));
return i;
}
var str = "some string to test";
alert(str.nthIndexOf("t", 3)); // 15
alert(str.nthIndexOf("t", 7)); // -1
alert(str.nthIndexOf("z", 4)); // -1
var sub = str.substr(str.nthIndexOf("t",3)); // "test"
Of course if you don't want to add the function to String.prototype you can have it as a stand-alone function by adding another parameter to pass in the string you want to search in.
If you want to stick to indexOf:
var string = "http://something/sth1/sth2/sth3/"
var lastIndex = string.indexOf("/", lastIndex);
lastIndex = string.indexOf("/", lastIndex);
lastIndex = string.indexOf("/", lastIndex);
string = string.substr(lastIndex);
If you want to get the path of that given URL, you can also use a RE:
string = string.match(/\/\/[^\/]+\/(.+)?/)[1];
This RE searches for "//", accepts anything between "//" and the next "/", and returns an object. This object has several properties. propery [1] contains the substring after the third /.
Another approach is to use the Javascript "split" function:
var strWord = "me/you/something";
var splittedWord = strWord.split("/");
splittedWord[0] would return "me"
splittedWord[1] would return "you"
splittedWord[2] would return "something"
It sounds like you want the pathname. If you're in a browser, keep an a element handy...
var _a = document.createElement('a');
...and let it do the parsing for you.
_a.href = "http://something.com/somethingheretoo";
alert( _a.pathname.slice(1) ); // somethingheretoo
DEMO: http://jsfiddle.net/2qT9c/
In your case, you could use the lastIndexOf() method to get the 3rd forward slash.
Here's a very cool way of handling this:
How can I remove all characters up to and including the 3rd slash in a string?
My preference of the proposed solutions is
var url = "http://blablab/test/page.php";
alert(url.split("/")[3]);
//-> "test"
Inestead of using indexOf it is possible to do this this way:
const url = 'http://something.com/somethingheretoo';
const content = new URL(url).pathname.slice(1);