This question already has answers here:
How to remove numbers from a string?
(8 answers)
Closed 3 years ago.
I have a few URL's like these
https://{Domain}/rent/abcdef/2019/Canada
https:/{Domain}/buy/Supported/2019/Gill-Avenue
I want to remove '2019'or any part which contain only numbers from these Url's so that the Url's look as below
https://{Domain}/rent/abcdef/Canada
https:/{Domain}/buy/Supported/Gill-Avenue
How can i achieve this using javascript
You can try this;
let str = "https://test.com/rent/abcdef/2019/Canada";
str.replace(/\/\d+/g, '');
You should try something like that:
split on '/', filter with a /d regex and rejoin with '/'
I can't try right now sorry
window.location.href.split('/').filter(substr => !(/^\d+$/.match(substr))).join('/')
Try to do this for the first:
var str = "https://example.com/rent/abcdef/2019/Canada"
str = str.replace(/[0-9]/g, '');
str = str.replace("f//", "f/");
And for the second:
var str = "https://example.com/rent/abcdef/2019/Canada"
str = str.replace(/[0-9]/g, '');
str = str.replace("d//", "d/");
So this is if you want to replace just 1 digit. The first one of each of these works but adds a new / backslash to the whole link after the last letter before the / in the old version. To remove that, you do the second, which contains the last letter to not remove the :// too. The way is to find the last letter of each of these numbers before the backslash after using the first replace() function and replace them to remove the extra backslash.
This might work for easy things, like if you already know the URL, but for complicated things like a very big project, this is no easy way to do it. If you want "easy", then check other answers.
As said, you can also do this:
let str = "https://test.com/rent/abcdef/2019/Canada";
var withNoNum = str.replace(/\/\d+/g, '');
This is going to remove groups of numbers. So I added a new string withNoNum which is str's replacement with no numbers, which might be more good because if you are doing a website that allows you to send your own website and remove the numbers from it to get a new site.
This also might help you with this problem: removing numbers from string
Related
This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 4 years ago.
I'm looking for some assistance with JavaScript/Regex when trying to format a string of text.
I have the following IDs:
00A1234/A12
0A1234/A12
A1234/A12
000A1234/A12
I'm looking for a way that I can trim all of these down to 1234/A12. In essence, it should find the first letter from the left, and remove it and any preceding numbers so the final format should be 0000/A00 or 0000/AA00.
Is there an efficient way this can be acheived by Javascript? I'm looking at Regex at the moment.
Instead of focussing on what you want to strip, look at what you want to get:
/\d{4}\/[A-Z]{1,2}\d{2}/
var str = 'fdfhfjkqhfjAZEA0123/A45GHJqffhdlh';
match = str.match(/\d{4}\/[A-Z]{1,2}\d{2}/);
if (match) console.log(match[0]);
You could seach for leading digits and a following letter.
var data = ['00A1234/A12', '0A1234/A12', 'A1234/A12', '000A1234/A12'],
regex = /^\d*[a-z]/gi;
data.forEach(s => console.log(s.replace(regex, '')));
Or you could use String#slice for the last 8 characters.
var data = ['00A1234/A12', '0A1234/A12', 'A1234/A12', '000A1234/A12'];
data.forEach(s => console.log(s.slice(-8)));
You could use this function. Using regex find the first letter, then make a substring starting after that index.
function getCode(s){
var firstChar = s.match('[a-zA-Z]');
return s.substr(s.indexOf(firstChar)+1)
}
getCode("00A1234/A12");
getCode("0A1234/A12");
getCode("A1234/A12");
getCode("000A1234/A12");
A regex such as this will capture all of your examples, with a numbered capture group for the bit you're interested in
[0-9]*[A-Z]([0-9]{4}/[A-Z]{1,2}[0-9]{2})
var input = ["00A1234/A12","0A1234/A12","A1234/A12","000A1234/A12"];
var re = new RegExp("[0-9]*[A-Z]([0-9]{4}/[A-Z]{1,2}[0-9]{2})");
input.forEach(function(x){
console.log(re.exec(x)[1])
});
This question already has answers here:
Regex: find whatever comes after one thing before another thing
(4 answers)
Reference - What does this regex mean?
(1 answer)
Closed 8 years ago.
For example I have a bunch of string of this format "/something/#wherever" "/some/#whatiwant"
I'm only interested in what comes after #'s in this case.
For the two suggested duplicates:
Regex: find whatever comes after one thing before another thing
The accepted answer is no where near as succinct as the one I accepted and honestly would have left me confused had I been able to think up a way to search for "regex find whatever comes after one thing before another thing"
Reference - What does this regex mean?
Is a reference manual for regex and not an answer to my question, if it were an answer to my question ALL regex questions should just be sent that direction, and are therefore duplicates.
In this example, capturing the non white space(for \S+) after the # in group-1.
var testString = "/some/#whatiwant";
var testOutput = testString.match(/#(\S+)/)[1];
// alert(testOutput);
If you want to use both # and # for parsing, then use character class []
var testOutput = testString.match(/[##](\S+)/)[1];
It depends on which flavor of regex you're using, but what you want is positive lookbehind:
(?<=#).*
This regex will match everything AFTER the hashtag, but not the hashtag itself.
EDIT: I didn't look at the javascript tag. js doesn't natively support lookbehind, so you'll have to use a capture group, like so:
var str = '/something/some#whatIwant',
reg = /#(.*)/;
alert(str.match(reg)[1]);
The regex would be [^#]+#(.+).
Try:
var arr = ["/something/#wherever","/some/#whatiwant"];
var reg = /[##](\w+)$/; // matchs after # and # signs
for ( var i = 0; i < arr.length; i++ ) {
console.log(reg.exec(arr[i])[1]);
}
RegExp match after # and # (if you don't want # to be matched onward just remove it from RegExp)
JSFIDDLE
This question already has answers here:
Parse query string in JavaScript [duplicate]
(11 answers)
Closed 8 years ago.
So let's say I have this HTML link.
<a id="avId" href="http://www.whatever.com/user=74853380">Link</a>
And I have this JavaScript
av = document.getElementById('avId').getAttribute('href')
Which returns:
"http://www.whatever.com/user=74853380"
How do I extract 74853380 specifically from the resulting string?
There are a couple ways you could do this.
1.) Using substr and indexOf to extract it
var str = "www.something.com/user=123123123";
str.substr(str.indexOf('=') + 1, str.length);
2.) Using regex
var str = var str = "www.something.com/user=123123123";
// You can make this more specific for your query string, hence the '=' and group
str.match(/=(\d+)/)[1];
You could also split on the = character and take the second value in the resulting array. Your best bet is probably regex since it is much more robust. Splitting on a character or using substr and indexOf is likely to fail if your query string becomes more complex. Regex can also capture multiple groups if you need it to.
You can use regular expression:
var exp = /\d+/;
var str = "http://www.whatever.com/user=74853380";
console.log(str.match(exp));
Explanation:
/\d+/ - means "one or more digits"
Another case when you need find more than one number
"http://www.whatever.com/user=74853380/question/123123123"
You can use g flag.
var exp = /\d+/g;
var str = "http://www.whatever.com/user=74853380/question/123123123";
console.log(str.match(exp));
You can play with regular expressions
Well, you could split() it for a one liner answer.
var x = parseInt(av.split("=")[1],10); //convert to int if needed
This question already has answers here:
Split string on the first white space occurrence
(16 answers)
Closed 10 years ago.
Forgive me if this is a double post, but I couldn't find a similair one that worked for me.
I have a domain name ex. google.co.uk (but this can also be google.com). I need to split this on the first period so I get an array object like this: ["google", "co.uk"] or ["google", "com"]
In antoher post I found this: 'google.co.uk'.split(/.(.+)?/)[1]; but that doesn't seem to work...
Can anyone help me? Thanks in advance!
Replace the first . with something else that will never turn up in the string (such as |), then split off that character.
As str.replace only replaces the first instance of the character it finds by default, the code is pretty simple:
str = "google.co.uk";
str.replace(".", "|").split("|");
jsFiddle
var text = 'google.co.uk';
//Returns the position of the first '.'
var index = text.indexOf('.');
//Grab the the start of the string up to the position of the '.'
var first = text.substring(0, index);
//Start from the '.' + 1(to exclude the '.') and go to the end of the string
var second = text.substring(index + 1);
alert(first); //google
alert(second); //co.uk
You're all making this a bit complicated. It's possible in one easy line:
var domain = 'google.co.uk';
alert(domain.split(/^(.+?)\./ig).splice(1));
You can use some native javascript functions...
string='google.com';
dot=string.indexOf('.',0);
name=string.substring(0,dot);
domain=string.substring(dot+1,string.length);
arr= new Array(name, domain);
alert(arr);
Lol, already see better solutions... :) and similar solutions too...
This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I have a simple string that I'm trying to manipulate:
Your order will be processed soon:
I grab the string using:
var html = jQuery('.checkout td h4').html();
I then try to replace the ':' using:
html.replace(":", ".");
When I print it out to the console, the string is the same as the original string. I've also tried making sure that the html variable is of type "string" by doing the following:
html = html + "";
That doesn't do anything. In searching around, it seems that the replace function does a RegEx search and that the ":" character might have a special meaning. I do not know how to fix this. Can someone help me get rid of this stinkin' colon?
Slightly related...
I couldn't get these answers to work to replace all ":" in a string for the url encoded character %3a and modified this answer by'xdazz' to work: Javascript: Replace colon and comma characters to get...
str = str.replace(/:\s*/g, "%3a");
In your case it would be
str = str.replace(/:\s*/g, ".");
If you wanted to replace all colons with periods on a longer string.
Hope this helps somebody else.
The replace function returns a new string with the replacements made.
Javascript strings are immutable—it cannot modify the original string.
You need to write html = html.replace(":", ".");
I think c++ is the only high level language where strings are mutable. This means that replace cannot modify the string it operates on and so must return a new string instead.
Try the following instead
var element = jQuery('.checkout td h4');
element.html(element.html().replace(":", "."));
Or, perhaps more correctly (since you may have multiple elements).
jQuery('.checkout td h4').html(
function (index, oldHtml) {
return oldHtml.replace(":", ".");
}
);