js split only until first given char - javascript

I got the following String
var intNote = "08.03.2018 09:53:37 - Mustermann, Max (Work notes) Work note internal"
which I manipulate the following way:
var tempArr = intNote.split('-');
var tempArr2 = tempArr[1].split('(Work notes)');
internalDate = tempArr[0]; // >> 08.03.2018 09:53:37
internalName = tempArr2[0]; // >> Mustermann, Max
internalNote = tempArr2[1]; // >> Work note internal
When I, for example, have the following String
var intNote = "08.03.2018 09:53:37 - Mustermann, Max (Work notes) Work
note - internal"
I get the result
internalNote = tempArr2[1]; // >> Work note
I know the 'problem' is the operator .split('-'). How can I define it to split only at the first given "-" that my result will be
internalNote = tempArr2[1]; // >> Work note - internal

Or you could use regex all the way.
/([^-]*)-(.*)\(Work notes\)(.*)/
will give you three capture groups (no. 1-3) with the strings you're after.
var intNote1 = "08.03.2018 09:53:37 - Mustermann, Max (Work notes) Work note internal",
intNote2 = "08.03.2018 09:53:37 - Mustermann, Max (Work notes) Work note - internal",
re = /([^-]*)-(.*)\(Work notes\)(.*)/,
arr;
arr=re.exec(intNote1);
arr.shift(); // Remove index 0 (full match)
document.write('<br/>1:' + intNote1 + '<br/>' + arr.join('<br/>'));
arr=re.exec(intNote2);
arr.shift(); // Remove index 0 (full match)
document.write('<br/><br/>2:' + intNote2 + '<br/>' + arr.join('<br/>'));

Instead of first split, use substring
var internalDate = intNote.substring( 0, intNote.indexOf( '-' ) );
var tempArr1 = intNote.substring( intNote.indexOf( '-' ) + 1 );
var tempArr2 = tempArr1.split('(Work notes)');
internalDate = tempArr[0]; // >> 08.03.2018 09:53:37

Provide a regex to split.
Check this.
var intNote = "08.03.2018 09:53:37 - Mustermann, Max (Work notes) Work note - internal"
var tempArr = intNote.split(/-(.+)/)
var tempArr2 = tempArr[1].split('(Work notes)');
internalDate = tempArr[0];
internalName = tempArr2[0];
internalNote = tempArr2[1];
console.log(internalDate)
console.log(internalName)
console.log(internalNote)

Related

Set the last number in a string to negative

I have a string with diffrent mathematical characters, and i want to make the last number negative/positive. Let's say the string is "100/5*30-60+333". The result i want is "100/5*30-60+(-333)", and i want to convert it back to positive ("100/5*30-60+333").
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = hiddenText.value;
n.split('+');
n.split('-');
n.split('*');
n.split('/');
console.log(n);
}
What i get is the whole hiddenText.value, and not an array of all numbers. Any tips?
First, I'd match all of the basic math operators to get their order:
const operatorsArr = n.match(/\+|\-|\/|\*/g)
Then, split the string:
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = hiddenText.value;
n = n.replace(/\+|\-|\/|\*/g, '|');
n = n.split('|');
console.log(n);
}
Then, you will have an array of numbers, in which you can mutate the last number easily:
n[n.lengh-1] *= -1;
Now we can combine the two arrays together:
let newArr;
for (let i = 0; i < n.length; i++) {
newArr.push(n[i]);
if (operatorsArr[i]) newArr.push(operatorsArr[i]);
}
At last, you can rejoin the array to create the new String with a seperator of your choosing. In this example I'm using a space:
newArr = newArr.join(' ')
Please let me know how that works out for you.
Let's say the string is "100/5*30-60+333". The result i want is
"100/5*30-60+(-333)", and i want to convert it back to positive
("100/5*30-60+333").
The following code does that:
let mathStr = '100/5*30-60+333';
console.log(mathStr);
let tokens = mathStr.split('+');
let index = tokens.length - 1;
let lastToken = tokens[index];
lastToken = '('.concat('-', lastToken, ')');
let newMathStr = tokens[0].concat('+', lastToken);
console.log(newMathStr); // 100/5*30-60+(-333)
console.log(mathStr); // 100/5*30-60+333
EDIT:
... and i want to convert it back to positive ("100/5*30-60+333").
One way is to declare mathStr (with the value "100/5*30-60+333") as a var at the beginning and reuse it, later as you need. Another way is to code as follows:
let str = "100/5*30-60+(-333)";
str = str.replace('(-', '').replace(')', '');
console.log(str); // 100/5*30-60+333
To get numbers You can use replace function and split check code bellow :
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = "100/5*30-60+333";
n = n.replace('+','|+');
n = n.replace('-','|-');
n = n.replace('*','|*');
n = n.replace('/','|/');
n=n.split('|');console.log(n);
// to use any caracter from array use it in removeop like example
// if we have array (split return) have 100 5 30 60 333 we get 100 for example
// we need to make removeop(n[0]) and that reutrn 100;
// ok now to replace last value to negative in string you can just make
// var lastv=n[n.length-1];
// n[n.length-1] ='(-'+n[n.length-1])+')';
//var newstring=n.join('');
//n[n.length-1]=lastv;
//var oldstring=n.join('');
}
function removeop(stringop)
{
stringop = stringop.replace('+','');
stringop = stringop.replace('-','');
stringop = stringop.replace('*','');
stringop = stringop.replace('/','');
return stringop;
}
If you really need to add "()", then you can modify accordingly
<script>
function myConversion(){
var str = "100/5*30-60-333";
var p = str.lastIndexOf("+");
if(p>-1)
{
str = str.replaceAt(p,"-");
}
else
{
var n = str.lastIndexOf("-");
if(n>-1)
str = str.replaceAt(n,"+");
}
console.log(str);
}
String.prototype.replaceAt=function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}
</script>

How to increment a string in JavaScript containing leading zeros?

I have string like:
MPG_0023
I want to find something like
MPG_0023 + 1
and I should get
MPG_0024
How to do that in JavaScript? It should take care that if there are no leading zeros, or one leading zero should still work like MPG23 should give MPG24 or MPG023 should give MPG024.
There should be no assumption that there is underscore or leading zeros, the only thing is that first part be any string or even no string and the number part may or may not have leading zeros and it is any kind of number so it should work for 0023 ( return 0024) or for gp031 ( return gp032) etc.
Here's a quick way without using regex.. as long as there's always a single underscore preceding the number and as long as the number is 4 digits, this will work.
var n = 'MPG_0023';
var a = n.split('_');
var r = a[0]+'_'+(("0000"+(++a[1])).substr(-4));
console.log(r);
Or if you do wanna do regex, the underscore won't matter.
var n = "MPG_0099";
var r = n.replace(/(\d+)/, (match)=>("0".repeat(4)+(++match)).substr(-4));
console.log(r);
You can use the regular expressions to make the changes as shown in the following code
var text = "MPG_0023";
var getPart = text.replace ( /[^\d.]/g, '' ); // returns 0023
var num = parseInt(getPart); // returns 23
var newVal = num+1; // returns 24
var reg = new RegExp(num); // create dynamic regexp
var newstring = text.replace ( reg, newVal ); // returns MPG_0024
console.log(num);
console.log(newVal);
console.log(reg);
console.log(newstring);
Using regex along with the function padStart
function add(str, n) {
return str.replace(/(\d+)/, function(match) {
var length = match.length;
var newValue = Number(match) + n;
return newValue.toString(10).padStart(length, "0");
});
}
console.log(add("MPG_023", 101));
console.log(add("MPG_0023", 101));
console.log(add("MPG_0000023", 10001));
console.log(add("MPG_0100023", 10001));
Using regular expression you can do it like this.
var text1 = 'MPG_0023';
var text2 = 'MPG_23';
var regex = /(.*_[0]*)(\d*)/;
var match1 = regex.exec(text1);
var match2 = regex.exec(text2);
var newText1 = match1[1] + (Number(match1[2]) + 1);
var newText2 = match2[1] + (Number(match2[2]) + 1);
console.log(newText1);
console.log(newText2);
Increment and pad the same value (comments inline)
var prefix = "MPG_"
var padDigit = 4; //number of total characters after prefix
var value = "MPG_0023";
console.log("currentValue ", value);
//method for padding
var fnPad = (str, padDigit) => (Array(padDigit + 1).join("0") + str).slice(-padDigit);
//method to get next value
var fnGetNextCounterValue = (value) => {
var num = value.substring(prefix.length); //extract num value
++num; //increment value
return prefix + fnPad(num, padDigit); //prepend prefix after padding
};
console.log( "Next", value = fnGetNextCounterValue(value) );
console.log( "Next", value = fnGetNextCounterValue(value) );
console.log( "Next", value = fnGetNextCounterValue(value) );
One way would e to split the string on the "_" character, increment the number and then add the zeros back to the number.
var testString = "MGP_0023";
var ary = testString.split("_");
var newNumber = Number(ary[1]) + 1;
var result = ary[0] + pad(newNumber);
// helper function to add zeros in front of the number
function pad(number) {
var str = number.toString();
while (str.length < 4) {
str = '0' + str;
}
return str;
}
You could cast to number, increment the value and cast back. Then check if you need leading zeros by looking at the length of the string.
Snippet below:
let str = "MPG_0023",
num = Number(str.substr(4)) + 1,
newStr = String(num);
function addLeading0(str) {
return str.length === 2 ? '00' + str : (str.length === 3 ? '0' + str : str);
}
console.log("MPG_" + addLeading0(newStr));

How to get the ID from this URL?

I need a way to get the ID ( 153752044713801 in this case ) of this page:
https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801
I tried this code but doen't work:
var str = 0, pagefb = 0;
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801';
var re1 = /^(.+)facebook\.com\/pages\/([-\w\.]+)\/([-\w\.]+)/;
if(re1.exec(fburl)){
str = re1.exec(fburl)[3];
pagefb = str.substr(str.lastIndexOf("-") + 1);
alert('ok');
}
try:
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801';
var parts = fburl.split("/");
var myId = parts[parts.length-1];
alert(myId);
Try this regular expression: ^(.+)facebook\.com\/pages\/.*\/(\d*)
(in JavaScript, you have to add "/" at the beginning and end of the pattern like you did before)
this works for me
fburl.split('/')[fburl.split('/').length-1]
You can split the string using .split("/"). More information is availible on MDN
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801';
var parts = fburl.split('/')
var myFacebookId = parts[parts.length - 1]
Basically it returns an array of the string split into multiple parts (at the character/s you put inside the brackets).
The parts[parts.length - 1] will get the last item in the array parts
Demo below (Don't worry about the document..., they just print out data):
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713‌​801/?ref=sfhsidufh';
var parts = fburl.split('/')
var myFacebookId = parts[parts.length - 1]
// If first digit is ?
if (myFacebookId[0] == '?') {
// Set myFacebookId to the second from last part
myFacebookId = parts[parts.length - 2]
}
document.write('MyFacebookId: ' + myFacebookId)

sprintf equivalent for client-side JavaScript

I know that console.log supports at least some of the basic features of printf from C through messing around, but I was curious of a way to take advantage of console.log's implementation to create something similar to sprintf. I know you can't simply use .bind or .apply since console.log doesn't actually return the string, so is there a way around this?
If this isn't actually possible, is there some other little-known native implementation that's only a few lines of code away from achieving sprintf in JavaScript?
For those who do not know what sprintf is exactly, here is some documentation from tutorialspoint. Example usage I'm looking for is below:
var string1 = sprintf("Hello, %s!", "world");
var string2 = sprintf("The answer to everything is %d.", 42);
Keep it simple
var sprintf = (str, ...argv) => !argv.length ? str :
sprintf(str = str.replace(sprintf.token||"$", argv.shift()), ...argv);
Since Javascript handles data types automatically, there is no need for type options.
If you need padding, "15".padStart(5,"0") = ("00000"+15).slice(-5) = "00015".
Usage
var sprintf = (str, ...argv) => !argv.length ? str :
sprintf(str = str.replace(sprintf.token||"$", argv.shift()), ...argv);
alert(sprintf("Success after $ clicks ($ seconds).", 15, 4.569));
sprintf.token = "_";
alert(sprintf("Failure after _ clicks (_ seconds).", 5, 1.569));
sprintf.token = "%";
var a = "%<br>%<br>%";
var b = sprintf("% plus % is %", 0, 1, 0 + 1);
var c = sprintf("Hello, %!", "world");
var d = sprintf("The answer to everything is %.", 42);
document.write(sprintf(a,b,c,d));
Try utilizing eval , .replace
var sprintf = function sprintf() {
// arguments
var args = Array.prototype.slice.call(arguments)
// parameters for string
, n = args.slice(1, -1)
// string
, text = args[0]
// check for `Number`
, _res = isNaN(parseInt(args[args.length - 1]))
? args[args.length - 1]
// alternatively, if string passed
// as last argument to `sprintf`,
// `eval(args[args.length - 1])`
: Number(args[args.length - 1])
// array of replacement values
, arr = n.concat(_res)
// `res`: `text`
, res = text;
// loop `arr` items
for (var i = 0; i < arr.length; i++) {
// replace formatted characters within `res` with `arr` at index `i`
res = res.replace(/%d|%s/, arr[i])
}
// return string `res`
return res
};
document.write(sprintf("%d plus %d is %d", 0, 1, 0 + 1)
+ "<br>"
+ sprintf("Hello, %s!", "world")
+ "<br>"
+ sprintf("The answer to everything is %d.", 42)
);

Split String in Half By Word

I'm in a situation where I'd like to take a string and split it in half, respecting words so that this string here doesn't get split into this str ing here, rather it would be split into this string here.
I figure a starting step would to be to split the string into an array based on spaces, then calculate length based on those pieces, but in my attempts longer strings end up being split up incorrectly.
Look for the first space before and after the middle, and pick the one closest to the middle.
Example:
var s = "This is a long string";
var middle = Math.floor(s.length / 2);
var before = s.lastIndexOf(' ', middle);
var after = s.indexOf(' ', middle + 1);
if (middle - before < after - middle) {
middle = before;
} else {
middle = after;
}
var s1 = s.substr(0, middle);
var s2 = s.substr(middle + 1);
Demo: http://jsfiddle.net/7RNBu/
(This code assumes that there actually are spaces on both sides of the middle. You would also add checks for before and after being -1.)
Edit:
The check that I talked about in the node would be done correctly like this:
if (before == -1 || (after != -1 && middle - before >= after - middle)) {
middle = after;
} else {
middle = before;
}
Here is a fiddle where you can edit the text and see the result immediately: http://jsfiddle.net/Guffa/7RNBu/11/
I wanted to leave this as a comment but do not have enough rep points. The top solution right now fails pretty easily because it does not check for "-1" when using the indexOf method. See this fiddle:
http://jsfiddle.net/7RNBu/7/
var s = "This is a long strinjjjjjjjjjjjjjjjjg";
var middle = Math.floor(s.length / 2);
var before = s.lastIndexOf(' ', middle);
var after = s.indexOf(' ', middle + 1);
if (middle - before < after - middle) {
middle = before;
} else {
middle = after;
}
var s1 = s.substr(0, middle);
var s2 = s.substr(middle + 1);
You might also care about newlines, tabs, as well as spaces, so I would use a regex like this:
var s = "this string here";
var idx = s.length / 2;
while (idx < s.length && s[idx].match(/\s/) == null)
idx++;
var s1 = s.substring(0, idx);
var s2 = s.substring(idx);
document.getElementById("s1").innerText = s1;
document.getElementById("s2").innerText = s2;
See this fiddle: http://jsfiddle.net/nS6Bj/5/
let str = 'qwerty';
let half = Math.floor(str.length / 2);
str = str.slice(0, half) + ' ' + str.slice(half, str.length);
//output
'qwe rty'
I first thought I had an off-by-one error, but I eventually worked through it. Here's a working example.
Now to break down the logic used:
var calculate = function(initialString) {
var halfwayPoint = Math.floor(initialString.length / 2);
var strArray = initialString.split(' ');
// Caluclate halfway point, then break string into words
var wordFlag; // Will be split point
var charCount = 0;
_.each( strArray, function(word, strArrayIndex) {
if (wordFlag) return false;
// If we have the location, exit
// If charCount is before the halfway point
// and the end of word is after halfway point
// Then set the flag
// We add strArrayIndex to the word length to include spaces
if (charCount <= halfwayPoint &&
((charCount + word.length + strArrayIndex) >= halfwayPoint) ) {
wordFlag = strArrayIndex;
return false;
}
// Increase charCount to be length at the end of this word
charCount += (word.length);
});
if (!wordFlag) return null;
// Split the word array by the flag we figured out earlier
var lineOneArray = strArray.slice(0, (wordFlag + 1));
var lineTwoArray = strArray.slice(wordFlag + 1);
// We now join the word arrays into a string, stripping beginning and ending spaces.
var stOne = (lineOneArray.join(' ')).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var stTwo = (lineTwoArray.join(' ')).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
// Finally return the split strings as an array.
return [stOne, stTwo];
};
If anyone sees holes in my logic, let me know! I'm pretty sure this works in most cases though.
If you'd like the second string to be longer than the first, (ie have the line break before rather than after the middle word), then don't add +1 to wordFlag.
This will split your string based on word count (not character count, so the exact length of each half could be quite different, depending on the placement of long & short words).
var s = "This is a string of filler text";
var pieces = s.split(" "),
firstHalfLength = Math.round(pieces.length/2),
str1 = "",
str2 = "";
for (var i = 0; i < firstHalfLength; i++){
str1 += (i!=0?" ":"") + pieces[i];
}
for (var i = firstHalfLength; i < pieces.length; i++){
str2 += (i!=firstHalfLength?" ":"") + pieces[i];
}
document.write(s);
document.write("<br />"+str1);
document.write("<br />"+str2);
// Output
This is a string of filler text
This is a string
of filler text
http://jsfiddle.net/daCrosby/7RNBu/2/
<h1>
<span>
// for first half start from 0 till middle
{title.substring(0, title.length / 2)}
</span>
<span>
// second half just point the starting point
{title.substring(title.length / 2)}
</span>
</h1>

Categories

Resources