I am joining together 3 variables into a filename seperated by a -- for use in another Cloud function. I do this with the following code below:
const newFileName = size + "--" + bytes + "--" + name + ".txt";
How can I seperate these later with Regex?
size (extract before first --)
bytes (extract after first --)
name (extract after second --)
If you always use the same extension .txt you might remove that part from the string and then split on --
let str = "aaa--bbb--ccc.txt";
[size, bytes, name] = str.substring(0, str.length - 4).split("--");
console.log(size);
console.log(bytes);
console.log(name);
Another option could be to split on either -- or on a pattern that would match the last dot followed by matching not a dot until the end of the string.
let str = "aaa--bbb--ccc.txt";
[size, bytes, name] = str.split(/--|\.[^.]+$/);
console.log(size);
console.log(bytes);
console.log(name);
If you use this regex, it will pull the three parts into 3 different capture groups named "size", "bytes", and "name":
^(?<size>.*?)\-\-(?<bytes>.*?)\-\-(?<name>.*?[.txt])$
In javascript, you can use this code to pull the groups out afterwards:
var reg = /^(?<size>.*?)\-\-(?<bytes>.*?)\-\-(?<name>.*?[.txt])$/
var matches = "123--456--test.txt".match(reg);
var size = matches["groups"]["size"]
var bytes = matches["groups"]["bytes"]
var name = matches["groups"]["name"]
Where the "123--456--test.txt" string is instead the string you want to pull the data out of.
EDIT:
Like StackSlave pointed out, named capture groups like above are not always supported. If you need to support a browser or language that can't deal with named groups, you can instead do this:
var reg = /^(.*?)\-\-(.*?)\-\-(.*?)$/
var matches = "123--456--test.txt".match(reg);
var size = matches[1]
var bytes = matches[2]
var name = matches[3]
EDIT EDIT:
To get the file name without extension, use this regex instead:
var reg = /(.*?)\-\-(.*?)\-\-(.*?)\./
var matches = "123--456--test.txt".match(reg);
var size = matches[1]
var bytes = matches[2]
var name = matches[3]
Here's a numeric example:
var str = 'size--bytes--name.ext', m = str.match(/^(.+)--(.+)--(.+)(?:\..+)$/);
console.log(m); console.log('size:'+m[1]); console.log('bytes:'+m[2]); console.log('name:'+m[3]);
Related
I have a VERY long string containing code from a Rich Text Editor. I need to split this up into 4 parts to save it to the database. I am doing this.
var fullPart = $('#summernote').summernote('code').replace("'", "\'");
var markupStr = fullPart.substring(0, 3000000);
var markupStr2 = fullPart.substring(3000000, 3000000);
var markupStr3 = fullPart.substring(6000000, 3000000);
var markupStr4 = fullPart.substring(6000000);
markupStr, markupStr3 and markupStr4 all contain values, but markupStr2 is empty. What am I doing wrong?
var markupStr2 = fullPart.substring(3000000, 3000000);
Explanation : Start and End index are same in this that is why you are getting empty results.
Check here for more information.
str.substring(indexStart[, indexEnd])
indexStart The index of the first character to include in the returned
substring.
indexEnd Optional. The index of the first character to exclude from
the returned substring.
This is a simple mistake. fullpart.substring(3000000,3000000) would return a string of length of 3,000,000 - 3,000,000 characters (0 characters). The correct way to do this is:
var fullPart = $('#summernote').summernote('code').replace("'", "\'");
var markupStr = fullPart.substring(0, 3000000);
var markupStr2 = fullPart.substring(3000000, 6000000);
var markupStr3 = fullPart.substring(6000000, 9000000);
var markupStr4 = fullPart.substring(12000000);
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 the following string of text:
textString1:textString2:textString3:textString4
I'm looking to capture each text string and assign them to variables.
I've somehow managed to come up with the following:
var errorText = 'AAAA:BBBB:CCCC:DDDD';
var subString, intro, host, priority, queue = '';
var re = /(.+?\:)/g;
subString = errorText.match(re);
intro = subString[0];
host = subString[1];
priority = subString[2];
//queue = subString[3];
console.log(intro + " " + host + " " + priority);
JS Bin Link
However, I'm having problems with:
capturing the last group, since there is no : at the end
the variables contain : which I'd like to strip
You don't need a regex for this - just use errorText.split(':') to split by a colon. It will return an array.
And if you then want to add them together with spaces, you could do a simple replace instead: errorText.replace(/:/g,' ').
use split method for this.it will return array of string then iterate through array to get string:
var errorText = 'AAAA:BBBB:CCCC:DDDD';
var strArr=errorText.split(':');
console.log(errorText.split(':'));
for(key in strArr){
console.log(strArr[key]);
}
i have a string like this .
var url="http://localhost/elephanti2/chaink/stores/stores_ajax_page/5/b.BusinessName/asc/1/11"
i want to get substrings
http://localhost/elephanti2/chaink/stores/stores_ajax_page
and
5/b.BusinessName/asc/1/11
i want to split string from the 7 th slash and make the two sub-strings
how to do this ??,
i looked for split()
but in this case if i use it i have to con-cat the sub-strings and make what i want . is there a easy way ??
try this one:
var url="http://localhost/elephanti2/chaink/stores/stores_ajax_page/5/b.BusinessName/asc/1/11";
var parts = url.split('/');
var p1 = parts.slice(0,6).join('/');
var p2 = parts.slice(7).join('/');
alert(p1);
alert(p2);
p1 should get the first part and p2 is the second part
You can try this regex. Generally if your url pattern always follow this structure, it will work.
var pattern = /(\w+:\/\/(\w+\/){5})/i;
var url = "http://localhost/elephanti2/chaink/stores/stores_ajax_page/5/b.BusinessName/asc/1/11";
var result = url.split(pattern);
alert(result[1]);
alert(result[3]);
Try this :
var str = 'http://localhost/elephanti2/chaink/stores/stores_ajax_page/5/b.BusinessName/asc/1/11',
delimiter = '/',
start = 7,
tokens = str.split(delimiter).slice(start),
result = tokens.join(delimiter);
var match = str.match(/([^\/]*\/){5}/)[0];
Find this fiddle
In Javascript, how can I trim a string by a number of characters from the end, append another string, and re-append the initially cut-off string again?
In particular, I have filename.png and want to turn it into filename-thumbnail.png.
I am looking for something along the lines of:
var sImage = "filename.png";
var sAppend = "-thumbnail";
var sThumbnail = magicHere(sImage, sAppend);
You can use .slice, which accepts negative indexes:
function insert(str, sub, pos) {
return str.slice(0, pos) + sub + str.slice(pos);
// "filename" + "-thumbnail" + ".png"
}
Usage:
insert("filename.png", "-thumbnail", -4); // insert at 4th from end
Try using a regular expression (Good documentation can be found at https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions)
I haven't tested but try something like:
var re = /(.*)\.png$/;
var str = "filename.png";
var newstr = str.replace(re, "$1-thumbnail.png");
console.log(newstr);
I would use a regular expression to find the various parts of the filename and then rearrange and add strings as needed from there.
Something like this:
var file='filename.png';
var re1='((?:[a-z][a-z0-9_]*))';
var re2='.*?';
var re3='((?:[a-z][a-z0-9_]*))';
var p = new RegExp(re1+re2+re3,["i"]);
var m = p.exec(file);
if (m != null) {
var fileName=m[1];
var fileExtension=m[2];
}
That would give you your file's name in fileName and file's extension in fileExtension. From there you could append or prepend anything you want.
var newFile = fileName + '-thumbnail' + '.' + fileExtension;
Perhaps simpler than regular expressions, you could use lastindexof (see http://www.w3schools.com/jsref/jsref_lastindexof.asp) to find the file extension (look for the period - this allows for longer file extensions like .html), then use slice as suggested by pimvdb.
You could use a regular expression and do something like this:
var sImage = "filename.png";
var sAppend = "-thumbnail$1";
var rExtension = /(\.[\w\d]+)$/;
var sThumbnail = sImage.replace(rExtension, sAppend);
rExtension is a regular expression which looks for the extension, capturing it into $1. You'll see that $1 appears inside of sAppend, which means "put the extension here".
EDIT: This solution will work with any file extension of any length. See it in action here: http://jsfiddle.net/h4Qsv/