Javascript substring not working as expected with long string - javascript

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);

Related

Javascript Regex get elements from text

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!

Most efficient way to extract parts of string

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

Remove part of string that contains a tag

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('<')));

Incrementing a number in a string

I have the following string: 0-3-terms and I need to increment the 3 by 20 every time I click a button, also the start value might not always be 3 but I'll use it in this example..
I managed to do this using substring but it was so messy, I'd rather see if it's possible using Regex but I'm not good with Regex. So far I got here, I thought I would use the two hyphens to find the number I need to increment.
var str = '0-3-terms';
var patt = /0-[0-9]+-/;
var match = str.match(patt)[0];
//output ["0-3-"]
How can I increment the number 3 by 20 and insert it back in to the str, so I get:
0-23-terms, 0-43-terms, 0-63-terms etc.
You're doing a replacement. So use .replace.
var str = '0-3-terms';
var patt = /-(\d+)-/;
var result = str.replace(patt,function(_,n) {return "-"+(+n+20)+"-";});
Another option is to use .split instead of regex, if you prefer. That would look like this:
var str = '0-3-terms';
var split = str.split('-');
split[1] = +split[1] + 20;
var result = split.join('-');
alert(result);
I don't understand why you are using regex. Simply store the value and create string when the button is called..
//first value
var value = 3;
var str = '0-3-terms';
//after clicking the button
value = value+20;
str = "0-" + value + "-terms"

How can I convert this into a integer in Javascript?

I asked a similar question yesterday .. If I have for example 0-9999 , how can I turn this into 09999 , basically removing the - and make it an integer in javascript ?
var = 0-9999
turn that into 9999 integer
or var = 2-9999 , turn that into 29999
Thanks a bunch
This should do the trick:
num = num.replace(/[^0-9]+/g, '') * 1;
It'll strip out any non-numeric characters and convert the variable into an integer. Here's a jsFiddle demonstration for you.
The most obvious and basic of solutions would be:
var s = "1-2345";
var t = s.replace("-","");
var i = parseInt(t,10);
But that's making a lot of assumptions and ignoring any errors.
Try this:
var i = '0-9999';
var int = Number(i.replace('-', ''));
window.alert(int);
Note in Firefox, parseInt() won't work with leading zeros unless you pass in a radix (this appears to be a bug):
var int = parseInt(i.replace('-', ''), 10);
Fiddler
Remember that
var x = 2-9999
is the same as
var x = -9997
because the dash is seen as a subtraction symbol unless you use quotation marks (Single or double, doesn't matter).
So, assuming that you properly quote the text, you can use the following function to always pull out a character that is in any given spot of the text (Using a zero-based index).
function extractChar(myString,locationOfChar){
var y = myString.substring(0,locationOfChar-1)
var z = myString.substring(locationOfChar+1)
var s = y.concat(z)
var i = parseInt(s,10)
return i
}
therefore
var i = extractChar("2-9999",1)
Will be the same as
var i = 29999

Categories