it didn't work on stackoverflow snippet but if you try on your local you will see it's going to work.
js give me a this result
cdn=//cdn.files.com/web
but I dont want to this line
cdn=
js must give me after from cdn= I mean result must be like this
//cdn.files.com/web
my all js is below so how to do that ?
var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];
// myScript now contains our script object
var queryString = myScript.src.replace(/^[^\=]+\??/,'');
alert(decodeURIComponent(queryString));
<script src="//domain.com/web/Assets/js/main.js?cdn=%2f%2fcdn.files.com%2fweb"></script>
<p></p>
var s = "cdn=//cdn.files.com/web";
s2 = s.substring(s.indexOf("cdn=")+4,s.length);
alert(s2);
this will substring from the index next to equals character to the end of yours string :)
fixed and tested
Split the string by '?cdn=' and get the part after that(second element in the result array, at index 1).
var queryString = myScript.src.split('?cdn=')[1];
FYI : If there is only one URL param then you can simply use = or cdn= for splitting.
You can use split:
yourvariable.split('=');
So whatever your arguments into GET, the odd param will get your desired result.
PS: Prefer just the = char, because you can work with whatever param you want into link gived by src.
why can't you use ^.+?cdn= in your regex?
this will give you strings after the cdn=
var myScript = '//domain.com/web/Assets/js/main.js?cdn=%2f%2fcdn.files.com%2fweb';
var queryString = myScript.replace(/^.+?cdn=/, '');
console.log(decodeURIComponent(queryString));
Solution with regex
var src = 'cdn=//cdn.files.com/web';
var url = src.replace(/^([^\=]+=)(.*)$/, '$2');
console.log(decodeURIComponent(url));
DEMO with explanation
Related
I have a url like the following
http://localhost:8000/test/
What is the tidiest way of getting test from this using plain javascript/jQuery?
You can do it easily like following using split() method.
var str = 'http://localhost:8000/test/';
var arr = str.split('/');
console.log(arr[arr.length-2])
The section of the URL you are referring to is called the path, in Javascript this can be accessed by reading the contents of the location.pathname property.
You can then use a regular expression to access only the final directory name (between the last two slashes).
Don't you guys like regex? I think it is simpler.
s = 'http://localhost:8000/test/';
var content = s.match(/\/([^/]+)\/[^/]*$/)[1];
JS split() function does magic with location.pathname .
var str = location.pathname.split('/');
var requiredString = str[str.length -2];
requiredString will contain required string, you may console log it by console.log(requiredString) or use it anywhere else in the program.
let arr = link.split('/');
let fileName = arr[arr.length - 2] + "/" + arr[arr.length - 1];
It will return all data after second last /.
You can use :
window.location.pathname
returns the path and filename of the current page.
with the split() function
To learn more about window.location in w3 School :
https://www.w3schools.com/js/js_window_location.asp
//window.location.pathname return /test
var path=window.location.pathname.split("/");
var page=path[0]; //return test`
I have the following string:
var fileName = $(this).val();
this will give me a result:
C:\fakepath\audio_recording_47.wav
what I want is to obtain : audio_recording_47.wav
so, I need to trim it but I don't know how using javascript
please help
filename.split('\\').reverse()[0];
This will split the path by slashes, to obtain each part. Then to keep it simple, i reverse the array, so the last part that you need is now the first; and get the first part.
Or, even more simply: filename.split('\\').pop(), which will get the last item from the array.
You could write a little function to return the base name of the path:
function basename(fn) {
var x = fn.lastIndexOf("\\");
if (x >= 0) return fn.substr(x + 1);
return fn;
}
var filename = basename($(this).val());
You can do like this:
var fileName = $(this).val();
var path = fileName.split('\\');
var lastValue = path[path.length-1];
console.log(lastValue);//audio_recording_47.wav
Or, the shorter way you can do like this:
var fileName = $(this).val();
var path = fileName.split('\\').slice(-1);//audio_recording_47.wav
This should do it:
var trimmedFileName = fileName.match(/[^\\]*$/);
It matches everything that isn't a \ until the end of the string.
You could use a regular expression, like this:
var fileName = this.value.replace(/(?:[^\\\/]*[\\\/])*/, '');
Also, there is no need to use that snippet of jQuery, as this.value is both faster and simpler.
I have a string like
/abc/def/hij/lmn.o // just a raw string for example dont know what would be the content
I want only /abc/def/hij part of string how do I do that.
I tried using .split() but did not get any solution.
If you want to remove the particular string /lmn.o, you can use replace function, like this
console.log(data.replace("/lmn.o", ""));
# /abc/def/hij
If you want to remove the last part after the /, you can do this
console.log("/" + data.split("/").slice(1, -1).join("/"));
# /abc/def/hij
you can do
var str = "/abc/def/hij/lmn.o";
var dirname = str.replace(/\/[^/]+$/, "");
Alternatively:
var dirname = str.split("/").slice(0, -1).join("/");
See the benchmarks
Using javascript
var x = '/abc/def/hij/lmn.o';
var y = x.substring(0,x.lastIndexOf("/"));
console.log(y);
var s= "/abc/def/hij/lmn.o"
var arr= s.split("/");
after this, use
arr.pop();
to remove the last content of the array which would be lmn.o, after which you can use
var new_s= arr.join("/");
to get /abc/def/hij
I have a url like this
http://example.com/param1/param2/param3
Please help me get the second last parameter using javascript. I searched and could only find regex method to find the last parameter. I am new to this. Any help would be greatly appreciated.
Thanks.
var url = 'http://example.com/param1/param2/param3';
var result= url.split('/');
var Param = result[result.length-2];
Demo Fiddle:http://jsfiddle.net/HApnB/
Split() - Splits the string into an array of strings based on the separator you mentioned
In the above , result will be an array that contains
result = [http:,,example.com,param1,param2,param3];
Basic string operations:
> 'http://example.com/param1/param2/param3'.split('/').slice(-2)[0]
"param2"
You can do this by:
document.URL.split("/");
var url='http://example.com/param1/param2/param3';
var arr = url.split('/');
alert(arr[arr.length-2]);
arr[arr.length-2] will contain value 'param2'. Second last value
var url = "http://example.com/param1/param2/param3";
var params = url.replace(/^http:\/\/,'').split('/'); // beware of the doubleslash
var secondlast = params[params.length-2]; // check for length!!
var url = "http://example.com/param1/param2/param3";
var split = url.split("/");
alert(split[split.length - 2]);
Demo: http://jsfiddle.net/gE7TW/
The -2 is to make sure you always get the second last
My favorite answer is the following from #Blender
'http://example.com/param1/param2/param3'.split('/').slice(-2)[0]
However all answers suffer from the edge case syndrome. Below are the results of applying the above to a number of variants of your input string:
"http://example.com/param1/param2/param3" ==> "param2"
"http://example.com/param1/param2" ==> "param1"
"http://example.com/param1/" ==> "param1"
"http://example.com/param1" ==> "example.com"
"http://example.com" ==> ""
"http://" ==> ""
"http" ==> "http"
Note in particular the cases of the trailing /, the case with only // and the case with no /
Whether these edge cases are acceptable is something you will need to determine within the larger context of your code.
Do not validate this answer, choose from amongst the others.
Just another alternate solution:
var a = document.createElement('a');
a.href = 'http://example.com/param1/param2/param3'
var path = a.pathname;
// get array of params in path
var params = path.replace(/^\/+|\/+$/g, '').split('/');
// gets second from last parameter; returns undefined if not array;
var pop = params.slice(-2)[0];
Is there a way to remove everything after a certain character or just choose everything up to that character? I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.
Like this
/Controller/Action?id=11112&value=4444
I want the href to be /Controller/Action only, so I want to remove everything after the "?".
I'm using this now:
$('.Delete').click(function (e) {
e.preventDefault();
var id = $(this).parents('tr:first').attr('id');
var url = $(this).attr('href');
console.log(url);
}
You can also use the split() function. This seems to be the easiest one that comes to my mind :).
url.split('?')[0]
jsFiddle Demo
One advantage is this method will work even if there is no ? in the string - it will return the whole string.
var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);
Sample here
I should also mention that native string functions are much faster than regular expressions, which should only really be used when necessary (this isn't one of those cases).
Updated code to account for no '?':
var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);
Sample here
var href = "/Controller/Action?id=11112&value=4444";
href = href.replace(/\?.*/,'');
href ; //# => /Controller/Action
This will work if it finds a '?' and if it doesn't
May be very late party :p
You can use a back reference $'
$' - Inserts the portion of the string that follows the matched substring.
let str = "/Controller/Action?id=11112&value=4444"
let output = str.replace(/\?.*/g,"$'")
console.log(output)
It works for me very nicely:
var x = '/Controller/Action?id=11112&value=4444';
var remove_after= x.indexOf('?');
var result = x.substring(0, remove_after);
alert(result);
If you also want to keep "?" and just remove everything after that particular character, you can do:
var str = "/Controller/Action?id=11112&value=4444",
stripped = str.substring(0, str.indexOf('?') + '?'.length);
// output: /Controller/Action?
You can also use the split() method which, to me, is the easiest method for achieving this goal.
For example:
let dummyString ="Hello Javascript: This is dummy string"
dummyString = dummyString.split(':')[0]
console.log(dummyString)
// Returns "Hello Javascript"
Source: https://thispointer.com/javascript-remove-everything-after-a-certain-character/
if you add some json syringified objects, then you need to trim the spaces too... so i add the trim() too.
let x = "/Controller/Action?id=11112&value=4444";
let result = x.trim().substring(0, x.trim().indexOf('?'));
Worked for me:
var first = regexLabelOut.replace(/,.*/g, "");
It can easly be done using JavaScript for reference see link
JS String
EDIT
it can easly done as. ;)
var url="/Controller/Action?id=11112&value=4444 ";
var parameter_Start_index=url.indexOf('?');
var action_URL = url.substring(0, parameter_Start_index);
alert('action_URL : '+action_URL);