Let's say I have a input box with the value of "foo_bar"
I want to assign foo to a variable, as well as bar. I never know the lengths of each of those. Essentially, anything to the left of the _ should be one variable, and everything to the right should be another.
How would you do this in jQuery?
You don't need jQuery for that, you can do it in plain JavaScript. A regular expression is one alternative, or if you know that you'll always have the '_' separator, you can use the indexOf method to find its position and split from there.
Or with an example:
var val = $("#inputId").val();
int separatorIndex = val.indexOf('_');
var first = val.substring(0, separatorIndex);
var second = val.substring(separatorIndex + 1);
You could use this code:
var str = "foo_bar"; // Change with input data
var index = str.indexOf("_");
if (index < 0) return false; // Change this with your '_' not found code
var foo = str.substr(0, index);
var bar = str.substr(index + 1);
var a = 'foo_bar';
var b = a.split('_');
var left = b[0];
var right = b[1];
For the sake of variety:
var
str = 'foo_bar',
left = /(.+)_/.exec(str)[1],
right = /_(.+)/.exec(str)[1]
Related
I would like to do is to come up with a custom Javascript function, that when a user calls to a string, will replace a segment of a string based on a number and a value
The number tells the function which segment value should be replaced after the Nth hyphen.
The value tells the function what the new string value replacement will be.
For example:
var x = '4-D-5200-P41-120-08C2-8131-0000-9'
var str = RepFinCode(x,2,'ABCD")
Therefore, after some processing...
str = '4-D-ABCD-P41-120-08C2-8131-0000-9'
This should do it:
var x = '4-D-5200-P41-120-08C2-8131-0000-9';
var n = 3;
var s = 'ABCD';
var r = new RegExp('(([^-]+-){' + n + '})[^-]+-');
document.getElementById('a').innerHTML = x.replace(r, '$1' + s + '-');
<div id='a'></div>
As stated in the comments, this is probably not the way to go - it doesn't shorten the code, is not faster, and not more readable.
I have a variable that returns me the url of an image, and in this url the id of the image can vary the quantity of numbers... what would be the best way to complement the id like this:
As it is: http://mydomain.com.br/arquivos/ids/1318090/94842_1.jpg
How to stay: http://mydomain.com.br/arquivos/ids/1318090-500-500/94842_1.jpg
In short, I need to add the "-500-500" into id
Sorry... A Example:
var a = "http://mydomain.com.br/arquivos/ids/1318090/94842_1.jpg";
var b = "-500-500";
var position = 43;
var output = [a.slice(0, position), b, a.slice(position)].join('');
console.log(output);
You can do something like following:
var url = "http://mydomain.com.br/arquivos/ids/1318090/94842_1.jpg";
var index = url.lastIndexOf("/");
var new_url = url.slice(0, index) + "-500-500" + url.slice(index);
link = link.split("/").reduce((r,c,i)=>r+c+i===5?"-500-500": "","").join("/");
Simply add it behind the 6th element ( that are seperated by / ) .
you have not shown any progress what you did! How about i gave you the hint?
assign a variable to your string, split it using \ and then find the exact occurrence to change by this [0] of course change the number according to your desire where change is required.
Now get your new string and concate with old in a way that you get desired results. Example
var str = "http://mydomain.com.br/arquivos/ids/1318090/94842_1.jpg";
var newstr = str.split('/')[5];
var prepstr = newstr + "something";
then finally,
str + prepstr;
I would like to remove or replace this string in an HTML file using javascript.
'<script src="../assets/js/somejs.js?1.0.953"></script>'
Trouble is, the version number "1.0.953" keeps changing so I can't use a simple string.replace
You could achieve this using the following Regex:
\?.*?\"
Or, more specifically
(\d+)\.(\d+)\.(\d+)
For matching the version number.
Utilizing the regex, you can replace the version number with a blank value.
Ok this is messy but it works...
String.prototype.replaceAnyVersionOfScript = function(target, replacement) {
// 1. Build the string we need to replace (target + xxx + ></script>)
var targetLength = target.length;
var targetStartPos = this.indexOf(target);
var dynamicStartPos = targetStartPos + targetLength;
var dynamicEndPos = this.indexOf('></script>', dynamicStartPos) + 10;
var dynamicString = this.substring(dynamicStartPos, dynamicEndPos);
var dymamicStringToReplace = target + dynamicString;
// 2. Now we know what we are looking for. We can replace it.
return this.replace(dymamicStringToReplace, replacement);
};
shellHTML = shellHTML.replaceAnyVersionOfScript('<script src="./assets/js/CloudZoom.js', '');
I have this URL:
http://test.com/en/country/city
Im using lastIndexOf to obtain "city" but I want to obtain "country"
window.location.href.substring(window.location.href.lastIndexOf('/') + 1);
Is this posible with lasIndexOf or there is another function available for this case?
Thank you in advance!
You can split your url by / and take needed element (first remove http:// part):
var str = 'http://test.com/en/country/city';
str = str.replace('http://', '');
var parts = str.split('/');
console.log(parts);
alert(parts[2]+', '+parts[3]);
Try:
var fragment = "http://test.com/en/country/city";
var array_fragment = fragment.split('/');
var city = array_fragment[array_fragment.length - 1]
var country = array_fragment[array_fragment.length - 2]
alert(country)
You could do something like this:
var url = "http://test.com/en/country/city"
var urlParts = url.split("/")
urlParts[urlParts.length - 1] (which would equal to "city")
urlParts[urlParts.length - 2] (which would equal to "country")
Basically split on each occurence of "/" and pick the correct item from the returned array.
Is this posible with lastIndexOf?
Yes, it is possible.
Let's say
x="http://test.com/en/country/city"
We get the position of the last /
y=x.lastIndexOf("/");//26
We get the position of the second last /
z=x.lastIndexOf("/",y-1);//18
To extract the country, we now use substring as follows
x.substring(z+1,y)//country
Use split function to get second last value.
Try this
var url='http://test.com/en/country/city';
var splitArray=url.split('/');
alert(splitArray[splitArray.length-2]);
Try something like this.
var url = window.location.href;
var urlArray = url.split("/");
urlArray[urlArray.length-1] //City
urlArray[urlArray.length-2] //Country
I have a string in JavaScript like this:
var str = "1:A;2:B;3:A;4:c;5:D";
How to retreive option in front of 2, that is B.
Presently am getting this using for loop by splitting the string every ;,
but I want to know if there is any better way to achieve this without using looping concept.
You can use the split function, as below;
var str = "1:A;2:B;3:A;4:c;5:D";
var result = str.split(":");
document.getElementById("Location").innerHTML = res[2];
If you know that this will be a pattern you can use something like:
var str = "1:A;2:B;3:A;4:c;5:D";
var i = 2;
console.log(str[str.indexOf(i)+2]);
//Output "B"
If you wanted to get the option in front of 2 you could use either:
a loop (preferred in my option)
indexOf
Javascript:
function getAnswer(str) {
var position = str.indexOf(';2:')
// not found in string, or '2' is the first answer
if(position === -1) {
return;
}
return str.substring(position - 1, position)
}
Might be recursive approach help you.
var str = "1:A;2:B;3:A;4:c;5:D",
arr = str.split(";"),
len = arr.length;
function getVal(len){
if(len !== 0){
getVal(len-1);
if(arr[len-1].indexOf(2) === 0){
console.log(arr[len-1].split(":")[1])
};
};
};
getVal(len);
RegExp
var num = '2';
"1:A;2:B;3:A;4:c;5:D".match((new RegExp(num+"\\:([\\S\\s]+?)\\;", "")))[1];
Fiddle
This uses RegExp (Regular Expressions) What this does is it will look for a '2' in the string, then get the option associated with it
Substring
I couldn't think of a better word so forgive me. You can use substring and .indexOf()
var num = '2',
string = "1:A;2:B;3:A;4:c;5:D",
index = string.indexOf(num+':');
string.substring(index+num.length+1,index+num.length+2);
Fiddle
Similar
The substring answer is a little easier to understand but the following does the sameish
var num = '2',
string = "1:A;2:B;3:A;4:c;5:D";
string[string.indexOf(num+':')+num.length+1];
Fiddle
Foolproof
This should work in most situations. This will also get the option if it is more than one letter long
var string = "1:A;2:B;3:A;4:c;5:D",
num = '2',
result;
if (string.indexOf(';'+num+':') < 0) {
result = string.match(new RegExp(num+"\\:([\\S\\s]+?)\\;", ""))[1];
} else {
result = string.match((new RegExp('\\;'+num+"\\:([\\S\\s]+?)\\;", "")))[1];
}
Shorter:
var string = "1:A;2:B;3:A;4:c;5:D", num = '2', result = string.indexOf(";"+num+":") < 0? string.match(new RegExp(num+"\\:([\\S\\s]+?)\\;",""))[1] : string.match(new RegExp("\\;"+num+"\\:([\\S\\s]+?)\\;",""))[1];
alert(result);
Fiddle (I have made it a one-liner)