Split a string at the first occurence of a string using Javascript - javascript

I've tried multiple solutions from other threads but nothing seems to work when the split flag is a string as well. In this case I need to separate the first " - " (space dash space) from the rest of the string, which contains other occurences of " - "
var string = "1 - 000 : 3 - loremipsum";
Looking for a resulting array of:
[1][000 : 3 - loremipsum]

Simple replace() will suffice if you want that expected output
var str = "1 - 000 : 3 - loremipsum"
console.log('['+str.replace(' - ', '][')+']')

You can split by " - " to get an array of the form:
["1", "000 : 3", "loremipsum"]
Then you can use destructuring assignment to separate the first element and the rest of the array (r) from each other, and use a template literal to form a string, with the rest of the array (r) joined back together with a hyphen:
const string = "1 - 000 : 3 - loremipsum";
const [first, ...r] = string.split(" - ");
const res = `[${first}][${r.join(" - ")}]`;
console.log(res);
Or if you want your result in an array, you can create an new array rather than using a template literal:
const string = "1 - 000 : 3 - loremipsum";
const [first, ...r] = string.split(" - ");
const res = [first, r.join(" - ")];
console.log(res);

You can try using substrings since you seem to be a beginner in javascript.
var string = "1 - 000 : 3 - loremipsum";
var start = string.indexOf(" - "); // find the first ocurance of space dash space
var result = [];
result.push(string.substr(0, start)); // string before " - "
result.push(string.substr(start+3)); // string after " - "
console.log(result);

You could split on your delimiter and then join all the elements after the first element:
const string = "1 - 000 : 3 - loremipsum"
const delimiter = " - "
const splitArray = string.split(delimiter)
const firstElement = splitArray[0]
const otherElementsJoined = splitArray.slice(1).join(delimiter)
const finalArray = [firstElement, otherElementsJoined]
console.log(finalArray)

You could try using match() here:
var string = "1 - 000 : 3 - loremipsum";
var first = string.match(/^(.*?) -/)[1];
var second = string.match(/^.*? - (.*)$/)[1];
var output = [first, second];
console.log(output);

Related

split a string from end till second space

I have a string i want to split it so that I can extract the name from the particular string.
let str = "CN=John Mcclau - i0c00cu,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";
let splitstr= str.substr(3, str.indexOf(' -'))
console.log(splitstr)
Sample str2 = "PN=Coey PT - ljooys4,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";
I am doing this way but it displays the " - " too. How can i fix it?
You can split twice, first on the '=' and taking the second index then on the '-' and taking the first index. Add a trim() and you're good to go
const getName = str => str.split('=')[1].split('-')[0].trim();
let str = "CN=John Mcclau - i0c00cu,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";
console.log(getName(str))
str2 = "PN=Coey PT - ljooys4,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";
console.log(getName(str2))
If you switch out substr() for slice() it works fine using the same start/end indices
const getName = str => str.slice(3, str.indexOf(' -'));
const str ='CN=John Mcclau - i0c00cu,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com',
str2 = "PN=Coey PT - ljooys4,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";
[str,str2].forEach(s=> console.log(getName(s)))

JavaScript: How can I split a decimal number into 2 part according to where the first zero occurs after a non-zero integer

Sorry if the title sounds confusing. Basically what I am trying to do is to split a decimal number like this 0.1000 into two part - 1. 0.1 and 000 so I can render them differently with different styles.
Check out this screenshot
All the numbers are represented in strings. The tricky part is that we cannot split the number using number.split('0') since we only want to split at the first zero that appears after a non-zero integer.
Not sure how I can do this.
If I did not misunderstand what you are trying to achieve, you can do it with a regex that only matches unlimited zeros that are at the end of the given string like follows:
function markNumber(num) {
return num.replace( /(0{1,})$/g, '<span>$1</span>')
}
const number = 1.2345670089
let renderStyle1 = ''
let renderStyle2 = ''
const string = String(number) + '.'
const parts = string.split('.')
const decimals = parts[1]
const decimalsArray = Array.from(decimals);
// From MDN: The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.
const firstIndexOfZero = decimalsArray.findIndex(x => x === '0');
// From MDN: The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
if(firstIndexOfZero === -1){
renderStyle1 = parts[0] + parts[1]
} else {
renderStyle1 = parts[0] + decimalsArray.slice(0, firstIndexOfZero).join('') // using .join method to convert array to string without commas
renderStyle2 = decimalsArray.slice(firstIndexOfZero, decimalsArray.length).join('') // using .join method to convert array to string without commas
}
console.log(renderStyle1) // "1234567"
console.log(renderStyle2) // "0089"
Messy, and, probably, can be improved, but this should work:
let re = /(\d*\.[1-9]*?)(0.*)/;
["1000", "1.01", "1.10", "1.000", "1.34043"].map((str) =>
str.split(re).filter((entry) => entry !== "")
);
Here's my regex function
const number = ['0.1000', '2.534300', '1.2000', '1.004334000'];
function split_float(num) {
const reg = /^(\d*\.\d*[^0])(0*)$/g;
const [, ...matches] = [...num.matchAll(reg)][0];
return matches;
}
console.log(number.map(split_float));
here is my answer. It uses split and substring to achieve what you want. Tried it in w3school's tryit editor. Handles all of your data in screenshot pretty well:
function myFunction() {
var str = "0.01200";
var partone = str.split(".")[0];
var temp = str.split(".")[1];
for (var i=0; i<temp.length; i++){
if (temp[i] != 0 && temp[i+1] == 0){
break;
}
}
var parttwo = temp.substring(i+1);
partone = partone + "." + temp.substring(0, i+1);
var res = "partOne = " + partone + " and partTwo = " + parttwo;
document.getElementById("demo").innerHTML = res;
}
Here is the screenshot:

translating a standard arithmetic string into a BODMAS string delimited by pipes

I need to find a way of translating a standard arithmetic formula written as a string into another string in the format of a calculation implements BODMAS as a stack of values and operations where each are delimited by a pipes read from left to right.
I do not want the result of the formula, I'm trying to write a javascript function that can be added to an HTML page where a user can enter a formula (example 10 * 6 / 2), have the formula validated, then translated into another formula (result is 10|6|multiply|2|divide). Its translating from one string format to another.
I already have another function that knows how to process formulas written this way, I just need to avoid forcing users to have to write a formula in an unfamiliar way so I need this translation done on the interface.
What I've tried so far is using a split function but I haven't been able to work out how to extend it to create the bodman_value. My javascript skills are basic as. Here's where I got to, any advice of how to approach it appreciated.
const str = '10 * 6 / 2';
const value_1 = str.split(' ');
console.log(value_1[0]);
// expected output: "10"
const operator_1 = str.split(' ');
console.log(operator_1[1]);
// expected output: "*"
const value_2 = str.split(' ');
console.log(value_2[2]);
// expected output: "6"
const operator_2 = str.split(' ');
console.log(operator_2[3]);
// expected output: "/"
const value_3 = str.split(' ');
console.log(value_3[4]);
// expected output: "2"
// expected output: Array ["10","*","6","/", "2"]
// assuming operator always at arroay 'odd' position (strCopy array is 0-4)
// count operators by number of odd positions in array
// then loop to get operator name of each array f_operator
IF strCopy.[i] = "*" THEN f_operator.[i] = "multiply"
IF strCopy.[i] = "+" THEN f_operator.[i] = "add"
IF strCopy.[i] = "-" THEN f_operator.[i] = "subtract"
IF strCopy.[i] = "/" THEN f_operator.[i] = "divide"
var bodman_value
// FOR loop f from 0 to array count
bodman_value = strCopy.[f]] + "|" + strCopy.[f+2] + "|" + operator.[f]
IF array count > 3
bodman_value = bodman_value + "|"
else
Thanks.
If you have the pattern
value [operator, value]+
you could just switch the repeating operator value parts to
value [value, operator]+
var operators = {
'*': 'multiply',
'/': 'divide'
},
string = '10 * 6 / 2',
tokens = string.split(/\s+/),
i = 0,
result = [tokens[i++]];
while (i < tokens.length) {
result.push(tokens[i + 1], operators[tokens[i]]);
i += 2;
}
console.log(result.join('|'));
An even shorter approach with a regular expression and a replacement function.
var operators = {
'*': 'multiply',
'/': 'divide',
'+': 'plus'
},
string = '24 + 6 / 10 * 100',
result = string.replace(/\s+([^\s]+)\s+([^\s]+)/g, (_, o, v) => `|${v}|${operators[o]}`);
console.log(result);

Formatting array elements into Uppercase and lower case format using JavaScript

I have an array of strings. I need to display those elements into proper format. Like this example.
let array1 = ["WORLDWIDE_AGRICULTURAL - CA"," WORLDWIDE_INDUSTRIAL - MX"]
I have to display it like below:
let formattedArray = ["Worldwide Agricultural - CA","Worldwide Industrial - MX"]
There are multiple of elements so I have to save formatted strings into array. I have tried but it is not coming properly.
Any help is much appreciated.
if(array1.indexOf("WORLDWIDE_AGRICULTURAL")>=0 || array1.indexOf(" WORLDWIDE_INDUSTRIAL") >=0){ var locname1 = array1.split('-'); var locname2 =locname1[0].trim(); var locname3 = locaname1[1].trim(); var formattedArray = locname2.toUpperCase()+ ' - '+locname3.toUpeerCase();
But, it is coming in uppercase and i have to all formatted elements into array.
You could use .map() with .replace() and the replacement method to convert your capital groups into lowercase groups like so:
const array1 = ["WORLDWIDE_AGRICULTURAL - CA"," WORLDWIDE_INDUSTRIAL - MX"];
const res = array1.map(str =>
str.replace(/(\w)(\w+)_(\w)(\w+)/g, (_, a, b, c, d) =>
`${a}${b.toLowerCase()} ${c}${d.toLowerCase()}`
).trim()
);
console.log(res);
The expression first matchs the first character in the string and groups that in group a. It then groups the remaining characters in group b up until the underscore. Then, it groups the first character after the underscore (group c). Lastly, it groups the remaining characters up to the next space. Using the replacement method, we can change group b to lowercase, and group d to lowercase, giving you a capitalized string.
An alternate approach which would require less grouping is to extract the first character from the first and second group, and capitalize the rest:
const array1 = ["WORLDWIDE_AGRICULTURAL - CA"," WORLDWIDE_INDUSTRIAL - MX"];
const res = array1.map(str =>
str.replace(/(\w+)_(\w+)/g, (_, [a, ...b], [c, ...d]) =>
`${a}${b.join('').toLowerCase()} ${c}${d.join('').toLowerCase()}`
).trim()
);
console.log(res);
let array1 = ["WORLDWIDE_AGRICULTURAL - CA", " WORLDWIDE_INDUSTRIAL - MX"];
function titleCase(str) {
var splitStr = str.toLowerCase().split(' ');
for (var i = 0; i < splitStr.length; i++) {
if (splitStr[i].length > 2) {
splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
} else {
splitStr[i] = splitStr[i].toUpperCase()
}
}
return splitStr.join(' ');
}
const formattedArray = array1.map((x) => titleCase(x));
console.log(formattedArray);
Here's what would match your current demonstrated requirement:
let array1 = ["WORLDWIDE_AGRICULTURAL - CA"," WORLDWIDE_INDUSTRIAL - MX"]
function formatter(str) {
let split = str.split("-")
let formattedFirst = split[0].replace(/_/g, " ")
.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
return `${formattedFirst} - ${split[1]}`
}
let convertedArray = array1.map(formatter)
console.log(convertedArray);
First, it seems like you only want to format whats before the ' - ' so we split on that. Then using replace we turn the _ into ' ' after which we can convert to title casing by capitalizing the first letter and lower casing the rest. Afterwards, we recombine to restore the original format of the rest of the string

JavaScript - How can I get the last different index in string but

Hi I'm going to make a calculator and I want a +/- button. I want to get the latest *, -, +, / in the string and define whats the laststring.
For example:
str="2+3*13"
I want this to be split into:
strA="2+3*"
strB="13"
Another example:
str="3-2+8"
Should split into:
strA="3-2+"
strB="8"
Use lastIndexOf and one of the substring methods:
var strA, strB,
// a generic solution for more operators might be useful
index = Math.max(str.lastIndexOf("+"), str.lastIndexOf("-"), str.lastIndexOf("*"), str.lastIndexOf("/"));
if (index < 0) {
strA = "";
strB = str;
} else {
strA = str.substr(0, index+1);
strB = str.substr(index+1);
}
You can use replace, match, and Regular Expressions:
str="3-2+8"
strA = str.replace(/\d+$/, "")
strB = str.match(/\d+$/)[0]
console.log(str, strA, strB);
> 3-2+8 3-2+ 8
You can use regular expression and split method:
var parts = "2 + 4 + 12".split(/\b(?=\d+\s*$)/);
Will give you and array:
["2 + 4 + ", "12"]
Couple of tests:
"(2+4)*230" -> ["(2+4)*", "230"]
"(1232-74) / 123 " -> ["(1232-74) / ", "123 "]
"12 * 32" -> ["12 * ", "32"]

Categories