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...
Related
This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 2 years ago.
I'm new to Regex and was wondering how to split this string s4://test-dev/prefixes/file.mxf into ['test-dev', 'prefixes/file.mxf']. I want it to work for an unknown file path.
Ex)
s4://test-dev/prefixes/file.mxf/newpath/anothernewpath into
['test-dev', 'prefixes/file.mxf/newpath/anothernewpath']
If you are using regex for splitting (which is not necessary) you can use this regex: s4:\/\/test-dev\/(.*) and use first group (first parentheses) as second string (first one is always same as i can see), but easiest way is to find position of third '/' with this var pos=str.split("/", i).join("/").length; and then find substring from that position to end: var res = str.substring(pos, str.length-pos);
Instead of splitting, use capture groups.
url.match(/^[^/]+:\/\/([^/]+)\/?(.*)/).slice(1)
Please check the code below:
let url = "s4://test-dev/prefixes/file.mxf/newpath/anothernewpath"
let match = url.match(/^s4:\/\/([\w-]+)\/(.+)$/)
let result = [match[1], match[2]]
console.log(result)
The result is:
[
"test-dev",
"prefixes/file.mxf/newpath/anothernewpath"
]
/^[\w+\:\/\/]+[-w+]/i
matches 'text-dev'
/w+\:\/\/[-w+]\/gi/
matches the rest
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
This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 9 years ago.
RegExp gurus, heed my call!
This is probably super simple, but I've painted myself in a mental corner.
Taking a regular URL, split after the ?, which gives a string like variable=val&interesting=something¬interesting=somethingelse I want to extract the value of interesting.
The name of the variable I'm interested in can be a substring of another variable.
So the match should be
either beginning of string or "&" character
followed by "interesting="
followed by the string I want to capture
followed by either another "&" or end of string
I tried something along the lines of
[\^&]interesting=(.*)[&$]
but I got nothing...
Update
This is to be run in a Firefox addon on every get request, meaning that jQuery is not available and if possible I would like to avoid the extra string manipulation caused by writing a function.
To me this feels like a generic "extract part of a string with regex" but maybe I'm wrong (RegEx clearly isn't my strong side)
simple solution
var arr = "variable=val&interesting=something¬interesting=somethingelse".split("&");
for(i in arr) {
var splits = arr[i].split("=");
if(splits[0]=="interesting") alert(splits[1]);
}
also single line match
"variable=val&interesting=something¬interesting=somethingelse".match(/(?:[&]|^)interesting=((?:[^&]|$)+)/)[1]
function getValue(query)
{
var obj=location.search.slice(1),
array=obj.split('&'),
len=array.length;
for(var k=0;k<len;k++)
{
var elm=array[k].split('=');
if(elm[0]==query)return elm[1];
}
}
This function directly extract the query URL and return the corresponding value if present.
//usage
var get=getValue('interesting');
console.log(get);//something
If you're using the Add-on SDK for Firefox, you can use the url module:
https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/url.html
This is much better than using regex.
This question already has answers here:
Remove everything after a certain character
(10 answers)
Closed 9 years ago.
I am trying to remove all characters from a string after a specified index. I am sure there must be a simple function to do this, but I'm not sure what it is. I am basically looking for the javascript equivalent of c#'s string.Remove.
var myStr = "asdasrasdasd$hdghdfgsdfgf";
myStr = myStr.split("$")[0];
or
var myStr = "asdasrasdasd$hdghdfgsdfgf";
myStr = myStr.substring(0, myStr.indexOf("$") - 1);
Use substring
var x = 'get this test';
alert(x.substr(0,8)); //output: get this
You're looking for this.
string.substring(from, to)
from : Required. The index where to start the extraction. First character is at index 0
to : Optional. The index where to stop the extraction. If omitted, it extracts the rest of the string
See here: http://www.w3schools.com/jsref/jsref_substring.asp
I'd recommend using slice as you can use negative positions for the index. It's tidier code in general. For example:
var s = "messagehere";
var message = s.slice(0, -4);
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(":", ".");
}
);