Removing https:// and .com from String - javascript

I am trying to convert a group of given URLs to another format I'll need in another part of the application.
So for the string https://www.myUrl.com/research/case-studies I need the following output:
myUrl/research/case studies
The following function I created manages just fine but I cannot help feeling I'm not being efficient enough by doing everything in just one line.
function generate_conversion(convert_input, url_format){
simple_urls = [];
var new_url = '';
$.each(convert_input, function(index, item) {
new_url = item.replace(/^(https?:\/\/)?(www\.)?(?:\.[a-z\.]+[\/]?)?/,'');
new_url = new_url.replace(/([.]\w+)$/, '');
new_url = new_url.replace(/.com/g, '');
simple_urls.push(new_url.replace(/-/g, ' '));
});
console.log(simple_urls);
}
Is there a more efficient or readable way to achieve the same result? I cannot use window.location.host or similar methods because the URLs are passed as simple strings.

depends on my understanding try this.,
var originalString="https://www.myUrl.com/research/case-studies";
var replacedString=originalString.replace("https://www.","")
console.log(replacedString);

Just do it
var str = "https://www.myUrl.com/research/case-studies";
var simple_url = str.substring(str.indexOf("www.")+4);
console.log(simple_url);

Related

trim a string path using javascript

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.

How to parse a url using Javascript and Regular Expression?

I want to parse some urls's which have the following format :-
var url ="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
Its not necessary that the domain name and other parts would be same for all url's, they can vary i.e I am looking at a general solution.
Basically I want to strip off all the other things and get only the part:
/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p
I thought to parse this using JavaScript and Regular Expression
I am doing like this:
var mapObj = {"/^(http:\/\/)?.*?\//":"","(&mycracker.+)":"","(&ref.+)":""};
var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
url = url.replace(re, function(matched){
return mapObj[matched];
});
But its returning this
http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43pundefined
Where am I not doing the correct thing? Or is there another approach with an even easier solution?
You can use :
/(?:https?:\/\/[^\/]*)(\/.*?)(?=\&mycracker)/
Code :
var s="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a";
var ss=/(?:https?:\/\/[^\/]*)(\/.*?)(?=\&mycracker)/;
console.log(s.match(ss)[1]);
Demo
Fiddle Demo
Explanation :
Why don't you just map a split array?
You don't quite need to regex the URL, but you will have to run an if statement inside the loop to remove specific GET params from them. In this particular case (key word particular) you just have to substring till the indexOf "&mycracker"
var url ="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
var x = url.split("/");
var y = [];
x.map(function(data,index) { if (index >= 3) y.push(data); });
var path = "/"+y.join("/");
path = path.substring(0,path.indexOf("&mycracker"));
Change the following code a little bit and you can retrieve any parameter:
var url = "http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
var re = new RegExp(/http:\/\/[^?]+/);
var part1 = url.match(re);
var remain = url.replace(re, '');
//alert('Part1: ' + part1);
var rf = remain.split('&');
// alert('Part2: ' + rf);
var part2 = '';
for (var i = 0; i < rf.length; i++)
if (rf[i].match(/(p%5B%5D|sid)=/))
part2 += rf[i] + '&';
part2 = part2.replace(/&$/, '');
//alert(part2)
url = part1 + part2;
alert(url);
var url ="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a";
var newAddr = url.substr(22,url.length);
// newAddr == "/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
22 is where to start slicing up the string.
url.length is how much of it to include.
This works as long as the domain name remains the same on the links.

how to convert to array in js?

I have this string which I want to convert to an array:
var test = "{href:'one'},{href:'two'}";
So how can I convert this to an array?:
var new = [{href:'one'},{href:'two'}];
It depends where you got it from..
If possible you should correct it a bit to make it valid JSON syntax (at least in terms of the quotes)
var test = '{"href":"one"},{"href":"two"}';
var arr = JSON.parse('[' + test + ']');
Notice the " around both keys and values.
(making directly var test = '[{"href":"one"},{"href":"two"}]'; is even better)
If you could modify the original string to be valid JSON then you could do this:
JSON.parse(test)
Valid JSON:
var test = '[{"href":"one"},{"href":"two"}]';
Using jQuery:
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
var jsonObj = $.parseJSON('[' + str + ']');
jsonObj is your JSON object.
If changing the string to be valid JSON is not an option, and you fully trust this string, and its origin then I would use eval:
var test = "{href:'one'},{href:'two'}";
var arr = eval("[" + test + "]");
On that last note, please be aware that, if this string is coming from the user, it would be possible for them to pass in malicious code that eval will happily execute.
As an extremely trivial example, consider this
var test = "(function(){ window.jQuery = undefined; })()";
var arr = eval("[" + test + "]");
Bam, jQuery is wiped out.
Demonstrated here

extract part of URL from parent URL

For this url
"http://testsite/sites/TestSubSite/objstrat/CultureConnection/Pages/default.aspx"
Trying to extract everything after enterprise/sites.
I want "/TestSubSite/objstrat/CultureConnection/Pages/default.aspx"
I can get the filename like this:
var filename = parenturl.substring(parenturl.lastIndexOf("/") + );
But not sure how to extract from the middle..
Using lastIndexOf will fail for any URI reference with / in the fragment or query, as in http://example.com/foo/bar#/baz/boo.
Libraries like Google Closure's Uri module can make this easy.
new goog.Uri(parenturl).getPath()
If your library of choice doesn't have URI support, then http://www.ietf.org/rfc/rfc3986.txt appendix B suggests
var urlRegex = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
var path = decodeURIComponent(urlRegex.exec(parenturl)[5]);
will get you the path part.
Once you've got the path, you can then strip off the /sites/ part by doing something like
var pathSuffix = path.replace(/^\/sites\//, '/');
I love Javascript with DOM element.
var link = document.createElement('a');
link.href = "http://testsite/sites/TestSubSite/objstrat/CultureConnection/Pages/default.aspx";
link.protocol;
link.hostname;
link.port;
link.pathname;
link.search;
link.hash;
link.host;
link.pathname.replace(/^\/sites/,"") // "/TestSubSite/objstrat/CultureConnection/Pages/default.aspx"
The easiest thing might be to use javascript's Split() function and rebuild the string from the resulting array (leaving out the first couple items)
var parenturl = "http://testsite/sites/TestSubSite/objstrat/CultureConnection/Pages/default.aspx";
var tokens = parenturl.split("/");
for(var i=0;i<tokens .length;i++)
{
console.log(tokens [i]);
}
Hows about:
var parenturl = "http://testsite/sites/TestSubSite/objstrat/CultureConnection/Pages/default.aspx";
var filename = parenturl.match(/\/sites(.*)$/)[1];
alert(filename);

Remove everything after a certain character

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);

Categories