how to use regular expression in javascript to extract value? - javascript

I want to use regular expression in javascript to extract values. The string is in this pattern "title{position}", how should i get title and position in this example?

Assuming that's all there is too it (no nesting of '{}'s or anything) (\w+)\{(\w+)\} will match that instance and group the results as groups 1 and 2. Do you need anything more complicated like a collection of many of these per string or is that enough?

Is that string everything? If so there's no need for matching. Just split the string!
var str = "foo{bar}";
var pieces = str.split(/\{|\}/);
var title = pieces[0];
var position = pieces[1];
alert("Title: " + title + "\nPosition: " + position);
Demonstrated here

If you did want to add results to a structure -
var arr = [];
var text = 'title{position}';
text.replace(/(\w+){(\w+)}/g, function(m, key, value){
//alert('title is-'+key);
//alert('position is-'+value);
arr.push({"title":key,"position":value});
});
console.log(arr);
Demo - http://jsfiddle.net/Sr6Ed/1/

Related

Split text with a single code

var objname = "Image1-123456-789.png"
quick question i wanted to split this text without match them together again.
here is my code
var typename = objname.split("-");
//so it will be Image1,123456,789.png
var SplitNumber = typename[1]+'-'+typename[2];
var fullNumber = SplitCode.split('.')[0];
to get what i wanted
my intention is to get number is there anyway i can split them without join them and split again ?
can a single code do that perfectly ? my code look like so many job.
i need to get the 123456-789.
The String.prototype.substring() method extracts the characters from a string, between two specified indices, and returns the new sub string.
This method extracts the characters in a string between "start" and "end", not including "end" itself.
var objname = "Image1-123456-789.png";
var newname = objname.substring(objname.indexOf("-")+1, objname.indexOf("."));
alert(newname);
An alternate can be using Join. You can use slice to fetch range of values in array and then join them using -.
var objname = "Image1-123456-789.png";
var fullnumber = objname.split("-").slice(1).join("-").split(".")[0];
alert(fullnumber)
Reference
Join Array from startIndex to endIndex
Here is your solution
var objname = "Image1-123456-789.png";
var typename= objname.split("-");
var again=typename[2];
var again_sep= again.split(".");
var fullNumber =typename[1]+'-'+again_sep[0];

get particular strings from a text that separated by underscore

I am trying to get the particular strings from the text below :
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
From this i have to get the following strings: "LAST", "BRANCH" and "JENKIN".
I used the code below to get "JENKIN";
var result = str.substr(str.lastIndexOf("_") +1);
It will get the result "JENKIN.bin". I need only "JENKIN".
Also the input string str sometimes contains this ".bin" string.
with substring() function you can extract text you need with defining start and end position. You have already found the start position with str.lastIndexOf("_") +1 and adding end position with str.indexOf(".") to substring() function will give you the result you need.
var result = str.substring(str.lastIndexOf("_") +1,str.indexOf("."));
It depends on how predictable the pattern is. How about:
var parts = str.replace(/\..+/, '').split('_');
And then parts[0] is 001AN, parts[1] is LAST, etc
You can use String.prototype.split to split a string into an array by a given separator:
var str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin';
var parts = str.split('_');
// parts is ['001AN', 'LAST', 'BRANCH', 'HYB', '1hhhhh5', 'PBTsd', 'JENKIN.bin'];
document.body.innerText = parts[1] + ", " + parts[2] + " and " + parts[6].split('.')[0];
You could do that way:
var re = /^[^_]*_([^_]*)_([^_]*)_.*_([^.]*)\..*$/;
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var matches = re.exec(str);
console.log(matches[1]); // LAST
console.log(matches[2]); // BRANCH
console.log(matches[3]); // JENKIN
This way you can reuse your RegExp anytime you want, and it can be used in other languages too.
Try using String.prototype.match() with RegExp /([A-Z])+(?=_B|_H|\.)/g to match any number of uppercase letters followed by "_B" , "_H" or "."
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var res = str.match(/([A-Z])+(?=_B|_H|\.)/g);
console.log(res)
I don't know why you want to that, but this example would be helpful.
It will be better write what exactly you want.
str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin'
find = ['LAST', 'BRANCH', 'JENKINS']
found = []
for item in find:
if item in str:
found.append(item)
print found # ['LAST', 'BRANCH']

Split the date! (It's a string actually)

I want to split this kind of String :
"14:30 - 19:30" or "14:30-19:30"
inside a javascript array like ["14:30", "19:30"]
so I have my variable
var stringa = "14:30 - 19:30";
var stringes = [];
Should i do it with regular expressions? I think I need an help
You can just use str.split :
var stringa = "14:30 - 19:30";
var res = str.split("-");
If you know that the only '-' present will be the delimiter, you can start by splitting on that:
let parts = input.split('-');
If you need to get rid of whitespace surrounding that, you should trim each part:
parts = parts.map(function (it) { return it.trim(); });
To validate those parts, you can use a regex:
parts = parts.filter(function (it) { return /^\d\d:\d\d$/.test(it); });
Combined:
var input = "14:30 - 19:30";
var parts = input.split('-').map(function(it) {
return it.trim();
}).filter(function(it) {
return /^\d\d:\d\d$/.test(it);
});
document.getElementById('results').textContent = JSON.stringify(parts);
<pre id="results"></pre>
Try this :
var stringa = "14:30 - 19:30";
var stringes = stringa.split("-"); // string is "14:30-19:30" this style
or
var stringes = stringa.split(" - "); // if string is "14:30 - 19:30"; style so it includes the spaces also around '-' character.
The split function breaks the strings in sub-strings based on the location of the substring you enter inside it "-"
. the first one splits it based on location of "-" and second one includes the spaces also " - ".
*also it looks more like 24 hour clock time format than data as you mentioned in your question.
var stringa = '14:30 - 19:30';
var stringes = stringa.split("-");
.split is probably the best way to go, though you will want to prep the string first. I would go with str.replace(/\s*-\s*/g, '-').split('-'). to demonstrate:
var str = "14:30 - 19:30"
var str2 = "14:30-19:30"
console.log(str.replace(/\s*-\s*/g, '-').split('-')) //outputs ["14:30", "19:30"]
console.log(str2 .replace(/\s*-\s*/g, '-').split('-')) //outputs ["14:30", "19:30"]
Don't forget that you can pass a RegExp into str.split
'14:30 - 19:30'.split(/\s*-\s*/); // ["14:30", "19:30"]
'14:30-19:30'.split(/\s*-\s*/); // ["14:30", "19:30"]

Cannot extract parts of a string

I have a string like this : SPList:6E5F5E0D-0CA4-426C-A523-134BA33369D7?SPWeb:C5DD2ADA-E0C4-4971-961F-233789297FE9:.
Using Javascript, I would like to extract the two IDs (which can be different) : 6E5F5E0D-0CA4-426C-A523-134BA33369D7 and C5DD2ADA-E0C4-4971-961F-233789297FE9.
I'm using this regular expression : ^SPList\:(?:[0-9A-Za-z\-]+)\?SPWeb\:(?:[0-9A-Za-z\-]+)\:$.
I expect this expression to extract into two matching groups the two IDs.
By now, my code is :
var input = "SPList:6E5F5E0D-0CA4-426C-A523-134BA33369D7?SPWeb:C5DD2ADA-E0C4-4971-961F-233789297FE9:";
var myregex = /^SPList\:(?:[0-9A-Za-z\-]+)\?SPWeb\:(?:[0-9A-Za-z\-]+)\:$/g;
var match = input.match(myregex);
var listId = match[0];
var webId = match[1];
However, this is not working as expected. The first match contains the whole string, and the second match is undefined.
What is the proper way to extract my ID's?
Here is a jsfiddle that illustrate my issue.
This should suit your needs:
var regex = /^SPList:([0-9A-F-]+)[?]SPWeb:([0-9A-F-]+):$/g;
var match = regex.exec(input);
var listId = match[1];
var webId = match[2];
I simply replaced the non-capturing groups of your initial regex by capturing groups, and used regex.exec(input) instead of input.match(regex) to get the captured data. Also, since the IDs seem to be hexadecimal values, I used A-F instead of A-Z.
try this:
var myregex = /[^\:]([0-9A-Z\-]+)[^\?|\:]/g;
var match = input.match(myregex);
alert("listID: " + match[1] + "\n" + "webID: " + match[3]);

Exclude characters from displaying?

I want to exclude characters from displaying in a vbulletin template.
For example, if a user writes:
"[Hello World] How are you?"
I want to ecxlude "[" and "]" all that's inside so it only displays:
"How are you?"
Is there a way to do this?
Use JavaScript string operations .getIndexOf() and .substring(). Get the position of the first bracket, get the position of the second bracket, split the string into 3 substrings, the middle section being between the two indexed values, and then add just the first and third substrings together. Like this:
var string = "[Hello World] How are you?";
var bracket1 = string.getIndexOf("[");
var bracket2 = string.getIndexOf("]");
var substring1 = string.substring(0,bracket1);
var substring2 = string.substring(bracket1,bracket2);
var substring3 = string.substring(bracket2,string.length);
var solution = substring 1 + " " + substring 3;
At least, that's the concept. Everything may not be right on, but you could futz with the numbers a little to get it perfect.
Or if you don't need to worry about what comes before [], simply use .split():
var string = "[Hello World] How are you?";
var solutionArray = string.split("]");
var solution = solutionArray[1];
Hope this helps!

Categories

Resources