Javascript Regex - Match everything after string [duplicate] - javascript

This question already has answers here:
Remove querystring from URL
(11 answers)
Closed 6 years ago.
I'm trying to use JS regex to drop everything after a string in my url. For example www.myurl/one/two/three/?a=b&c=d I want to drop everything after the string "three/". How would I write a regex to match this?

Try this one:
function getPathFromUrl(url) {
return url.split("?")[0];
}
var url = 'www.myurl/one/two/three/?a=b&c=d';
var result = getPathFromUrl(url);
alert(result);

Here's one quick way.
var str = 'www.myurl/one/two/three/?a=b&c=d'
var newStr = str.replace(/(.*\/three\/).*/, '$1')
alert(newStr)

Use built-in ability to manipulate URLs.
var a = document.createElement('a');
a.href = "http://www.myurl/one/two/three/?a=b&c=d";
a.search = '';
console.log(a.href);
Notes:
The search property of the a element refers to the portion starting with the question mark.
The http:// is required here; otherwise, the URL will be interpreted as relative to the current URL.
If you would prefer to use a regexp, then you could erase everything starting with the question mark:
"www.myurl/one/two/three/?a=b&c=d".replace(/\?.*/, '')
Or, you could match what you DO want to keep, such as everything up to the question mark, using:
"www.myurl/one/two/three/?a=b&c=d".match(/.*(?=\?)/)[0]
You need the [0] since match returns an array, whose first element is the entire match. The ?= here is a look-ahead. Actually that is the same as
"www.myurl/one/two/three/?a=b&c=d".match(/[^?]+/)[0]
Or, if you want to match up to three/ specifically:
"www.myurl/one/two/three/?a=b&c=d".match(/.*three\//)[0]

Or basicaly with methods of String and Array :
var string = "www.myurl/one/two/three/?a=b&c=d";
var array = string.split('/');
array.pop();
var result = array.join("/");
console.log(result); //www.myurl/one/two/three

Related

How to check "#" tag is there or not in a string? [duplicate]

This question already has answers here:
How to tell if a string contains a certain character in JavaScript?
(21 answers)
Closed 4 years ago.
I'm a beginner in node.js so please do excuse me if my question is foolish. As we know we can use
var regex = /[ !##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g;
regex.test(str);
to check whether a string contains special charecters or not .But what I'm asking is how to check for only a particular charecter means how can I check only presence of #.
I tried to do
var regex = /[#]/g; regex.test(str).
Although it's not working but are there any other method of doing this?
You don't need a regex to find a single character in a string. You can use indexOf, like this:
var hasHashtag = str.indexOf('#') >= 0;
This returns true if the character is in the string.
Use includes to check the existence of # in your string. You don't actually require regex to do that.
var str = 'someSt#ring';
var res = str.includes('#');
console.log(res);
str = 'someSt#ri#ng';
res = str.includes('#');
console.log(res);
str = 'someString';
res = str.includes('#');
console.log(res);
Use indexOf
str.indexOf('#') >= 0;

Tricky RegEx Capture [duplicate]

This question already has answers here:
My regex is matching too much. How do I make it stop? [duplicate]
(5 answers)
Closed 6 years ago.
I've got a couple strings and I need to pull characters out that appear between double quotes. The problem is, I want to grab them in groups.
var str = 'FF\"J"A4"L"';
var results = str.match(/\"(.*)\"/);
This returns everything between the first and last double quote. In this case it returns J"A4"L but what I need it to return is J and L.
The content between quotes is pretty much any unicode character like letters and numbers including as }, =, and #.
Any ideas on how to complete this with regex?
It sounds like the content between quotes is any character except for a quote, in which case you can get away with
/"([^"]*)"/
what you're looking for is this with the /g "global flag":
/("[^"]*")/g
In your example, it's like this:
var str = 'FF\"J"A4"L"';
var results = str.match(/("[^"]*")/g);
When doing this, results would be [""J"", ""L""], which contains the entire match (which is why the extra quotes are there).
If you wanted just the matched groups (which returns just the groups, not the whole match area), you would use exec:
var str = 'FF\"J"A4"L"';
var results = []
var r = /("[^"]*")/g
match = r.exec(str);
while (match != null) {
results.push(match[1])
match = r.exec(str);
}
Now, results is ["J", "L"]

Replace substring with edited substring [duplicate]

This question already has answers here:
Why isn't this split in javascript working?
(2 answers)
Closed 8 years ago.
please, could you help me with my task: I need to replace part of string and probably the best way is regular expression but I don't know, how to make it working. I want to do this:
http://someweb.com/section/&limit=10&page=2
replace page=2 with page=3 so string will be:
http://someweb.com/section/&limit=10&page=3
I tried to do something like this:
// set string in t variable
t.replace('/page=[0-9]/', 'page=$1++') });
Thank you very much for your help :)
In our case first argument should be regexp, but in your variant this is string '/page=[0-9]/' (remove '). In replace you can pass function as second argument, and do with matched data what you want. (for example add +1 to page=)
var str = "http://someweb.com/section/&limit=10&page=2";
str.replace(/page=(\d+)/, function (match, page) {
return 'page=' + (+page + 1); // plus before page converts string to number
});
Example
You can also try below code.
var url = "http://someweb.com/section/&limit=10&page=2",
reExp = /page=([0-9])+/,
result = reExp.exec(url);
url = url.replace(reExp, 'page=' + (+result[1] + 1));
console.log(url)

Cut off extension of filename [duplicate]

This question already has answers here:
Regex for everything before last forward or backward slash
(3 answers)
Closed 5 years ago.
I have a list of filenames like
index.min.html
index.dev.html
index.min.js
index.dev.js
There.are.also.files.with.multiple.dots.and.other.extension
I want to cut off the extensions of the filenames, but the problem is that I can only use match for this task.
I tried many regular expressions looking like "index.min.html".match( /^((?!:(\.[^\.]+$)).+)/gi ); to select the filename without the last dot and extension, but they selected either the hole filename, nothing or the part before the first dot. Is there a way to select only the filename without extension?
Why regex? Simple substring expressions make this a lot simpler:
var filename = 'index.something.js.html';
alert(filename.substr(0, filename.lastIndexOf(".")));
I'd go for
/(.+)\..+$/mi
demo # regex101
See the demo, especially the matches. It only gives you the filename without the last . and the characters afterwards.
How about this one: (.*)\.[^\.]+
See http://regex101.com/r/xI6qM0
A simpler solution would be to just slice off the last element:
var a = "index.min.html";
var b = a.split('.').slice(0, -1).join('.');
Or, even better, using JavaScript's String function substr:
var b = a.substr(0, a.lastIndexOf("."));
Why do you have to use match?
Could do the trick, too:
function baseName(str) {
if (typeof str !== 'string') return;
var frags = str.split('.')
return frags.splice(0,frags.length-1).join('.');
}
Repl:http://repl.it/OvI
jsPerf: http://jsperf.com/string-extension-splits
Result:
substr is the fastest of all options in this thread. Kudos to the other guys.

How can I get the last character in a string? [duplicate]

This question already has answers here:
How can I get last characters of a string
(25 answers)
Closed 10 years ago.
If I have the following variable in javascript
var myString = "Test3";
what is the fastest way to parse out the "3" from this string that works in all browsers (back to IE6)
Since in Javascript a string is a char array, you can access the last character by the length of the string.
var lastChar = myString[myString.length -1];
It does it:
myString.substr(-1);
This returns a substring of myString starting at one character from the end: the last character.
This also works:
myString.charAt(myString.length-1);
And this too:
myString.slice(-1);
var myString = "Test3";
alert(myString[myString.length-1])
here is a simple fiddle
http://jsfiddle.net/MZEqD/
Javascript strings have a length property that will tell you the length of the string.
Then all you have to do is use the substr() function to get the last character:
var myString = "Test3";
var lastChar = myString.substr(myString.length - 1);
edit: yes, or use the array notation as the other posts before me have done.
Lots of String functions explained here
myString.substring(str.length,str.length-1)
You should be able to do something like the above - which will get the last character
Use the charAt method. This function accepts one argument: The index of the character.
var lastCHar = myString.charAt(myString.length-1);
You should look at charAt function and take length of the string.
var b = 'I am a JavaScript hacker.';
console.log(b.charAt(b.length-1));

Categories

Resources