Extract words with RegEx - javascript

I am new with RegEx, but it would be very useful to use it for my project. What I want to do in Javascript is this :
I have this kind of string "/this/is/an/example" and I would like to extract each word of that string, that is to say :
"/this/is/an/example" -> this, is, an, example. And then use each word.
Up to now, I did :
var str = "/this/is/a/test";
var patt1 = /\/*/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
and it returns me : /,,,,,/,,,/,,/,,,,,
I know that I will have to use .slice function next if I can identify the position of each "/" by using search for instance but using search it only returns me the index of the first "/" that is to say in this case 0.
I cannot find out.
Any Idea ?
Thanks in advance !

Use split()
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
var str = "/this/is/a/test";
var array = str.split('/');
console.log(array);
In case you want to do with regex.
var str = "/this/is/a/test";
var patt1 = /(\w+)/g;
var result = str.match(patt1)
console.log(result);

Well I guess it depends on your definition of 'word', there is a 'word character' match which might be what you want:
var patt1 = /(\w+)/g;
Here is a working example of the regex
Full JS example:
var str = "/this/is/a/test";
var patt1 = /(\w+)/g;
var match = str.match(patt1);
var output = match.join(", ");
console.log(output);

You can use this regex: /\b[^\d\W]+\b/g, to have a specific word just access the index in the array. e.g result[0] == this
var str = "/this/is/a/test";
var patt1 = /\b[^\d\W]+\b/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
<span id="demo"></span>

Related

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"]

Replace strings from left until the first occuring string in Javascript

I am trying to figure out how to replace example:
sw1_code1_number1_jpg --> code1_number1_jpg
hon2_noncode_number2_jpg --> noncode_number2_jpg
ccc3_etccode_number3_jpg --> etccode_number3_jpg
ddd4_varcode_number4_jpg --> varcode_number4_jpg
So the results are all string after the first _
If it doesn't find any _ then do nothing.
I know how to find and replace strings, str.replace, indexof, lastindexof but dont know how remove up to the first found occurrence.
Thank You
Use the replace method with a regular expression:
"sw1_code1_number1_jpg".replace(/^.*?_/, "");
You could split your string and get a slice
var str = 'sw1_code1_number1_jpg';
var finalStr = str.split('_').slice(1).join('_') || str;
If your original string does not contain an underscore, then it returns the original string.
UPDATE A simpler one with slice (still works with strings not containing underscores)
var str = 'sw1_code1_number1_jpg';
var finalStr = str.slice(str.indexOf('_') + 1);
This one works in all cases because when no underscore is found, -1 is returned and as we add 1 to the index we call str.slice(0) which is equal to str.
There are several approaches you can take:
var str = 'sw1_code1_number1_jpg';
var arr = str.split('_');
arr.shift();
var newSfr = arr.join('_');
Or you could use slice or replace:
var str = 'sw1_code1_number1_jpg';
var newStr = str.slice(str.indexOf('_')+1);
Or
var newStr = 'sw1_code1_number1_jpg'.replace(/^[^_]+_/,'');

How to use Javascript slice to extract first and last letter of a string?

How to use JavaScript slice to extract the first and last letter of a string?
Eg: "Hello World"
I need the result as "dH".
Following is my jsfiddle :
http://jsfiddle.net/vSAs8/
Here's the cleanest solution :
var output = input.slice(-1)+input[0];
If you want more slice, there's also
var output = input.slice(-1)+input.slice(0,1);
And here are alternate fun (and less efficient) solutions :
var output = input.replace(/^(.).*(.)$/,'$2$1');
or
var output = input.match(/^.|.$/g).reverse().join('');
Substr works as well:
alert(test.substr(-1,1) + test.substr(0,1));
a.charAt(a.length-1) + a.charAt(0)
var str = " Virat Kohali "
var get_string_label = function(str){
str = str.split(" ");
str = str.filter(res=>res.length>0);
str = str.map(function(res){
return res[0].toUpperCase();
});
str = str.join("");
return str;
};
console.log(get_string_label(str));
str.split(" "); method splits a String object into an array of strings by separating the string into substrings, where it will find space in string.
then str.filter(res=>res.length>0) will filter out string having zero length (for "virat kohali" string you will get empty sub-string)
after that using map function you can fetch your first letter

Javascript regex value search

After reading the post here, I tried to get the value by regex as below:
var myString = "<a href='/search.html?id=HDJ&area=ASD&estate=JKG&ppt=3'></a>";
var myRegexp = /&estate=(.*?)(?:\s|$)/g;
var match = myRegexp.exec(myString);
match[1]
The result was JKG&propertytype=3'></a>, but I only want JKG. Strictly speaking I want the value between &estate= and &ppt Could someone suggest how to do that?
Thanks
A Regular Expression:
/&estate=(.*?)&ppt=/g
Note: I wouldn't recommend using regular expressions to parse query strings. It's brittle. Consider if the variables in the query string change order. If that can be the case, I recommend reading - Parse query string in JavaScript.
do:
var myString = "<a href='/search.html?id=HDJ&area=ASD&estate=JKG&ppt=3'></a>";
var myRegexp = /estate=(.*)&ppt=/g;
var match = myRegexp.exec(myString);
console.log( match[1] );
If only the solution is important then you can use the following:
var myString = "<a href='/search.html?id=HDJ&area=ASD&estate=JKG&ppt=3'></a>";
var indx1 = mystring.indexOf("&estate=") + 8;
var indx2 = mystring.indexOf("&ppt");
var neededString = mystring.substring(indx1, indx2);
Just exclude ampersands from the selection:
var myRegexp = /&estate=([^&]+)/g;
You might want to change it to this, in case estate is the first parameter:
var myRegexp = /[\?&]estate=([^&]+)/g;
jsFiddle
Based on your result value, just split it at the ampersand, no new or alternate regex required.
JavaScript:
var myString = "<a href='/search.html?id=HDJ&area=ASD&estate=JKG&ppt=3'></a>";
var myRegexp = /&estate=(.*?)(?:\s|$)/g;
var match = myRegexp.exec(myString);
var value = match[1].split('&')[0];
alert( value );

Categories

Resources