I'm doing a tracking application for my company and I really need your help
I've got some strings that display it wrong
I'll get the postcode/zipcode and the city name and the "function" (for example distrubition basis)
The string I get is something like that (it's swiss and the format is postcode cityname function)
place = "5506 MägenwilDistributionsbasis";
now postcode is "5506"
cityname is "Mägenwil"
function is "Distributionsbasis"
my question is how can I split the cityname and function (for this example now)?
is it possible to do it with regex or an if statement?
You can split the string using the following regexp:
var myString = "5506 MägenwilDistributionsbasis";
var units = /(\d+ )([A-Z][^A-Z]+)(.+)/g.exec(myString);
Check out contents of array units: there you see units[0] is the whole string, and units[1], units[2], units[3] are what you need.
Note According to comments I must say, it's just a draft for possible solution to let you understand how to start working on the problem in JS. So when you will test your application with more complicated city names and function names in the "magic string", try to figure out what regexp fits your purposes perfectly, because ([A-Z][^A-Z]+) definitly will not match all the known city names.
You could implement that in the most primitive way. Something like this:
place = "5506 MägenwilDistributionsbasis";
var codeAndNameAndFunction = place.split(" ");
var code = codeAndNameAndFunction[0];
var nameAndFunction = codeAndNameAndFunction[1];
var startOfTheFunction;
for (var i = 1, len = nameAndFunction.length; i < len; i++) {
myCharacter = nameAndFunction.charCodeAt(i);
if (myCharacter >= 65 && myCharacter <= 90) {
startOfTheFunction = i;
break;
}
}
var name = nameAndFunction.slice(0, startOfTheFunction);
var functionName = nameAndFunction.slice(startOfTheFunction,nameAndFunction.length);
This is a slight modification of Florian Peschka's answer:
You can split the string using the following regexp:
var myString = "5506 Yverdon-les-BainsDistributionsbasis";
var units = /(\d+ )(.+)([A-Z][^A-Z]+)/g.exec(myString);
Check out contents of array units: there you see units[0] is the whole string, and units[1], units[2], units[3] are what you need.
Note that this will only work if the "function" name is always in the form of Capital Letter followed by Non-capital letters.
Related
I'm quite new to the javascript world an have no idea about regex; I hope you can help me with that one:
I need a function that gives me the elements of a text-block that a user can input through an <input/ on a website, so i can output them to another <input/.
Generalized input:
txt1/txt2_txt3#txt4_txt5#txt6
Real input-example ("personalcode"):
user/855042,5_512125#2431072,25_729106#coursname optionaladdition
What I got so far is the html stuff and this (-yep thats not much):
var base= document.getElementsByName("personalcode")[0].value;
What I would need to get out is:
var one = txt1; //always letters
var two = txt2; //always a decimal number
var three = txt3; //always a decimal number
var four = txt4; //always a decimal number
var five = txt5; //always a decimal number
var six = txt6; //can be letters and decimal numbers
There will never be special characters such as !"§$%&/()=?+*# inside a text element. ö, ü, ä is possible.
Example:
var one = user;
var two = 855042,5;
var three = 512125;
var four = 2431072,25;
var five = 729106;
var six = coursname optionaladdition;
In the end I want to output it like this:
document.getElementsByName("output-user")[0].value= one;
.
.
.
I hope you understand what I mean.
var str = "user/855042,5_512125#2431072,25_729106#coursname optionaladdition";
var arr = str.split(/\/([\d,]+)_([\d,]+)#([\d,]+)_([\d,]+)#/);
# => ["user", "855042,5", "512125", "2431072,25", "729106", "coursname optionaladdition"]
I hope i understand you right what you want to achieve.
I made a small fiddle for you how to get your Data.
https://jsfiddle.net/zasg4zgx/6/
Here is the Code:
<form>
Login :
<input id="logthis" type="text" name="fnName" value="user/855042,5_512125#2431072,25_729106#coursname Löcher in Socken flicken">
<input type="button" value="Login" onClick="javascript:SeperateLoginString(logthis.value)">
</form>
With the id i can transfer the Value of the login field to the function.
function SeperateLoginString(logData) {
var seperateString = [];
var temp = new String(logData);
temp = temp.replace(/#/g, ' ').replace(/_/g, ' ').replace(/#/g, ' ').replace(/\//g, ' ');
seperateString = temp.split(" ");
var user = seperateString[0];
var value1 = seperateString[1];
var value2 = seperateString[2];
var value3 = seperateString[3];
var value4 = seperateString[4];
var value5 = seperateString[5];
With this loop you can add the "optionaladdition" to your value.
I managed it so it can have more than one value
for (var i = 6; i < seperateString.length; i++) {
value5 += " " + seperateString[i];
}
alert(value5);
}
Regards,Miriam
Since you are asking for six different variables, I suggest you use six different input tags. This would be easier for the user and especially for you as a developer. Parsing strings like this is asking for trouble.
However, you could get the values from the string using regex. For example, if you want your first variable (letters only), you could do something like this:
var 1 = text.match(/([A-z])+\//g).slice(0, - 1);
It basically matches a group of characters that starts with letters and ends with a forward slash. The slice method removes the last character from the string (the forward slash).
The second var could be selected like this:
var 2 = text.match(/([0-9])+\#/g).slice(0, - 1);
Still, I recommend you to just use multiple inputs. It's way cleaner and less prone to errors. Good luck!
I have a bunch of strings in the format 'TYPE_1_VARIABLE_NAME'.
The goal is to get 3 variables in the form of:
varType = 'TYPE',
varNumber = '1',
varName = 'VARIABLE_NAME'
What's the most efficient way of achieving this?
I know I can use:
var firstUnderscore = str.indexOf('_')
varType = str.slice(0, firstUnderscore))
varNumber = str.slice(firstUnderscore+1,firstUnderscore+2)
varName = str.slice(firstUnderscore+3)
but this feels like a poor way of doing it. Is there a better way? RegEx?
Or should I just rename the variable to 'TYPE_1_variableName' and do a:
varArray = str.split('_')
and then get them with:
varType = varArray[0],
varNumber = varArray[1],
varName = varArray[2]
Any help appreciated. jQuery also ok.
Regex solution
Given that the first and second underscores are the delimiters, this regex approach will extract the parts (allowing underscores in the last part):
//input data
var string = 'TYPE_1_VARIABLE_NAME';
//extract parts using .match()
var parts = string.match(/([^_]+)_([^_]+)_([^$]+)/);
//indexes 1 through 3 contains the parts
var varType = parts[1];
var varNumber = parts[2];
var varName = parts[3];
Given that the first variable consists of characters and the second of digits, this more specific regex could be used instead:
var parts = string.match(/(\w+)_(\d)_(.+)/);
Non-regex solution
Using .split('_'), you could do this:
//input data
var string = 'TYPE_1_VARIABLE_NAME';
//extract parts using .split()
var parts = string.split('_');
//indexes 0 and 1 contain the first parts
//the rest of the parts array contains the last part
var varType = parts[0];
var varNumber = parts[1];
var varName = parts.slice(2).join('_');
In matters of efficiency, both approaches contain about the same amount of code.
You could use regex and split
var string='TYPE_1_VARIABLE_NAME';
var div=string.split(/^([A-Z]+)_(\d+)_(\w+)$/);
console.log('type:'+div[1]);
console.log('num:'+div[2]);
console.log('name:'+div[3]);
Here's an answer I found here:
var array = str.split('_'),
type = array[0], number = array[1], name = array[2];
ES6 standardises destructuring assignment, which allows you to do what Firefox has supported for quite a while now:
var [type, number, name] = str.split('_');
You can check browser support using Kangax's compatibility table.
Here's a sample Fiddle
I have a variable in JavaScript that holds the below value:
<label>AAA</label>
I need just the AAA. I try to replace the characters but it is failing. Would someone please suggest the best approach?
var company="<label>AAA</label>";// I am getting this value from element
var rx = new RegExp("((\\$|)(([1-9]\\d{0,2}(\\,\\d{3})*|([1-9]\\d*))(\\.\\d{2})))|(\\<)*(\\>)");
var arr = rx.exec(company);
var arr1 = company.match(rx);
if (arr[1] != null) {
var co = arr[1].replace(",", "");
}
}
As you say you need only AAA, consider the below code.
I have taken a substring between the first '>' character in the string company, added 1 to that and the last < character. However, if the company var contains more of such < or >, you could go for a regex approach.
var company="<label>AAA</label>";
alert(company.substring(company.indexOf('>')+1, company.lastIndexOf('<')));
I have a string with keywords, separated by comma's.
Now I also have a nice RegEx, to filter out all the keywords in that string, that matches a queried-string.
Check out this initial question - RegEx - Extract words that contains a substring, from a comma seperated string
The example below works fine; it has a masterString, and a resultString. That last one only contains the keywords that has at least the word "car" in it.
masterString = "typography,caret,car,align,shopping-cart,adjust,card";
resultString = masterString.match(/[^,]*car[^,]*/g);
console.log(resultString);
Result from the code above;
"caret", "car", "shopping-cart", "card"
But how can I use the RegEx, with a variable matching-word (the word "car" in this example static and not variable).
I think it has to do something with a RegExp - but I can't figure out...
Here's a general solution for use with regexes:
var query = "anything";
// Escape the metacharacters that may be found in the query
// sadly, JS lacks a built-in regex escape function
query = query.replace(/[-\\()\[\]{}^$*+.?|]/g, '\\$&');
var regex = new RegExp("someRegexA" + query + "someRegexB", "g");
As long as someRegexA and someRegexB form a valid regex with a literal in-between, the regex variable will always hold a valid regex.
But, in your particular case, I'd simply do this:
var query = "car";
var items = masterString.split(",");
query = query.toLowerCase();
for (var i = 0; i < items.length; ++i) {
if (items[i].toLowerCase().indexOf(query) >= 0) {
console.log(items[i]);
}
}
How about this one?, you only need to replace \ \ with String , and it works for me. it can find whether your string has "car", not other similar word
var query = 'car';
var string = "car,bike,carrot,plane,card";
var strRegEx = '[^,]*'+query+'[,$]*';
string.match(strRegEx);
Answer provided by OP and removed from inside the question
I figured out this quick-and-maybe-very-dirty solution...
var query = 'car';
var string = "car,bike,carrot,plane,card";
var regex = new RegExp("[^,]*|QUERY|[^,]*".replace('|QUERY|',query),'ig');
string.match(regex);
This code outputs the following, not sure if it is good crafted, 'though..
"car", "carrot", "card"
But ended figuring out another, much simpler solution;
var query = "car";
var string = "car,bike,carrot,plane,card";
string.match(new RegExp("[^,]*"+query+"[^,]*",'ig'));
This code outputs the string below;
["car", "carrot", "card"]
My app-search-engine now works perfect :)
I have written a little JQuery / Javascript add on for our form, that takes a single full name input and breaks it into first and last name components. It opens a modal if there are three or more names in the input and asks which combo is correct.
My next step is finding and stripping any suffix that may have been entered such as Jr, Sr, III, etc. I am currently stripping off the last four characters and checking them with indexOf to see if they contain a suffix string (Jr, Sr, III, etc). But each line checks only one possible suffix and I am wondering is there is some js magic that will check multiple suffixs in one line. My current code is below:
var nameVal = $('#name').val();
var suffix = nameVal.slice(-4);
if (suffix.toLowerCase().indexOf(" jr") != -1) {
var nameSplit = nameVal.slice(0, -3).split(" ");
} elseif (suffix.toLowerCase().indexOf(" iii") != -1) {
var nameSplit = nameVal.slice(0, -4).split(" ");
} else {
var nameSplit = nameVal.split(" "); }
I can always do the good old || and keep adding extra (suffix.toLowerCase().indexOf(" jr") != -1) with a different indexOf value, but I am hoping to keep the code more compact if possible, my "little" script is already 3k.
Once I get this sorted the last step will be figuring out how to retain the last name value, so that further down the form when other names are entered and the script is called again it can check to see if the selected last name matches the new entry and bypass the modal pop up.
You can use a regular expression. Try something like this;
nameVal = nameVal.replace(/ (jr|sr|I?II)$/gi, "");
In more detail;
(jr|sr|I?II) = jr or sr or II or III
$ = at the end of line
/i = case insensitive
/g match globally
Probably best to use regexps for this, for example:
var names = [
"Joe Jr.",
"Mark Sr.",
"Loui III",
"Mark Lockering",
];
var suffixRes = [
/Jr\.$/, /Sr\.$/, 'III',
];
$(names).each(function(i, name) {
var str = name;
$(suffixRes).each(function(j, suffixRe) {
str = str.replace(suffixRe, '');
});
console.log(str);
});
Live example:
http://jsfiddle.net/am7QD/
In this case I usually make an array of values, (because I'm not good with regex)
var suffixArr = [' jr',' iii', ' ii'];
//then run a loop
for(var i = 0; i < suffixArr.length;i++){
if(suffixArr[i].toLowerCase().indexOf(suffixArr[i]) != -1){
nameSplit = nameVal.slice(0, - suffixArr[i].length).split(" ");
}
}