JS split regex by two different character - javascript

I have 2 strings:
"test:header_footer"
"test_3142"
I want to get array:
array = "test:header_footer".split(":") // ['test', 'header_footer']
array2 = "test_3142".split("_") // ['test', '3142']
Can I combine this with a regex expression to get the same result?
function(s) {
retutn s.split(/:|_/) // return bad value
}
So if string contain ':' - not separate by second '_'

You could write a one line method to check for : and split based on that condition.
var text = "your:string";
var array = text.split(text.indexOf(":") >= 0 ? ":" : "_"); // ['your', 'string']
var text2 = "your_string";
var array2 = text.split(text.indexOf(":") >= 0 ? ":" : "_"); // ['your', 'string']
var text3 = "your:other_string";
var array3 = text.split(text.indexOf(":") >= 0 ? ":" : "_"); // ['your', 'other_string']
This will check for :, if that is found then split by :, otherwise split by _.

You can use the includes method on your String to determine if there's a : present. If there is split the String by the colon, otherwise split the String by the underscore.
split_string = s => s.includes(":") ? s.split(":") : s.split("_");
//test strings
let str = "my:string_demo",
str2 = "my_string_demo",
str3 = "myString:demo_thing",
//string function
split_string = s => s.includes(":") ? s.split(":") : s.split("_");
console.log(
str, split_string(str)
);
console.log(
str2, split_string(str2)
);
console.log(
str3, split_string(str3)
);

Related

Turn Currency into Integer in Javascript

How to replace or convert $ 10.000,00 into number 10000 without $ in the beginning and ,00 in the end in Javascript?
I would do it using regex replaces:
var input = "$ 10.000,00";
var output = input
.replace(/,.*/g, '') // cut off ',' and after
.replace(/\D/g, ''); // remove non-digit characters
// or in one go:
// var output = input.replace(/,.*|\D/g, '');
output = parseInt(output, 10); // convert to Number
console.log(output); // 10000
Here you go, could be done easily though.
let price = "$ 10.000,00"
price = parseInt(price.split('.').join("").replace(/\$/g,'')).toFixed(0)
console.log(price)
You can try string replace.
let str = "$ 10.000,00";
// swap the places for , and .
let newstr = str.replace(/[.,]/g, ($1) => {
return $1 === '.' ? ',' : '.'
})
let num = newstr.replace(/[$,]/g, "");
console.log(num)
console.log(Number(num)) // convert it into number
console.log(parseFloat(num)) // or this
Support for more entries:
const toNumber = n => parseFloat(n.replace(/(?:^\D+)?(\d+)\.(\d{3})(,(\d+))?/, "$1$2.$4"))
console.log(toNumber("$ 10.000,00"))
console.log(toNumber("$ 10.000,69"))
console.log(toNumber("$ 10.000,00"))
console.log(toNumber("10.050,00"))
console.log(toNumber("10.981"))

Replace every nth character equal to "x"

I have a string where common characters are repeated.
For example
x1234,x2345,x3456,x4567,x5678,x6789
I'm trying to replace every nth occurrence of the character "x" starting from the first occurrence with the character "d" using javascript.
The final output should be as follows
d1234,x2345,d3456,x4567,d5678,x6789
You could add a counter and replace by using a remainder for checking.
function replace(string, char, repl, n) {
var i = 0;
return string.replace(new RegExp(char, 'g'), c => i++ % n ? c : repl);
}
console.log(replace('x1234,x2345,x3456,x4567,x5678,x6789', 'x', 'd', 2));
console.log(replace('x1234,x2345,x3456,x4567,x5678,x6789', 'x', 'd', 3));
function replaceNth(str, n, newChar) {
const arr = str.split(',');
return arr.map((item, i) => (i % n === 0) ? item.replace('x', newChar) : item).join(",")
}
const str = 'x1234,x2345,x3456,x4567,x5678,x6789';
// replace for every second string value
console.log(
replaceNth(str, 2, 'd')
);
// replace for every third string value
console.log(
replaceNth(str, 3, 'e')
);
var splittedWords = "x1234,x2345,x3456,x4567,x5678,x6789".split(",")
var result = splittedWords.map((element, index) => index % 2 ? element : "d" + element.substring(1))
console.log(result.join(","))
Can use a regular expression to match a pattern
var str1 = "x1234,x2345,x3456,x4567,x5678,x6789"
var result1 = str1.replace( /x([^x]+(x|$))/g, 'd$1')
console.log(result1)
var str2 = "x1234,x2345,x3456"
var result2 = str2.replace( /x([^x]+(x|$))/g, 'd$1')
console.log(result2)
Explanation of reg exp: RegExper
or can just do a simple split, map, join
var str = "x1234,x2345,x3456,x4567,x5678,x6789"
var result = str.split(",") // split on comma
.map((part,index) => // loop over array
index % 2 === 0 // see if we are even or odd
? "d" + part.substring(1) // if even, remove first character, replace with 1
: part) // if odd, leave it
.join(",") // join it back together
console.log(result)
This assumes that the x is always after the comma, which may or may not be true. If not, then the logic needs to be more complicated.

Find and split string at index of 2 symbols

I'm doing some localization coding and I'm trying to separate possible alternatives. For example, I want to get 'en' from 'en-US' or 'en_US'. I've already worked out how to do it for the first option but I'm looking for the cleanest way to do it for both the hyphen and the underscore. I first want to check if it can be split so I don't end up with 'en' and 'en' for both the primary and alternate locales.
if (currLoc && currLoc.indexOf('-') > -1) {
altLoc = currLoc.substring(0, currLoc.indexOf('-'));
}
If you expect the string not to be arbitrary but only as en-US or en_US or empty or en. Try this code.
if(curLoc) {
altLoc = currLoc.replace('-', '_').split('_')[0];
}
Actually if currLoc is empty string the if(curLoc) condition can be omitted, your altLoc in this case will also be empty string.
How about
if ( currLoc ){
if( currLoc.indexOf('-') > -1)
altLoc = currLoc.substring(0, currLoc.indexOf( '-' ));
else if( currLoc.indexOf('_') > -1 )
altLoc = currLoc.substring(0, currLoc.indexOf( '_' ));
}
var matches = new RegExp(/(.{2}).[-_](.{2})/gi).exec("fdgf-fed");
if (matches != null)
altLoc = matches[1];
var str = 'en_US';
var str1 = 'en-US';
var arr = str.replace(/[_-]/g, " ").split(" ");
arr[0] //en
arr[1] //US
var arr1 = str1.replace(/[_-]/g, " ").split(" ");
arr1[0] //en
arr1[1] //US
For a regex method you can use:
var reg = new RegExp(/^([a-z]{2})[^0-9]|[^a-z]|[^A-Z].+/g);
var result = reg.exec(text);
//result[1] <-- first group: "en" in case of "en_Us,en_US,en-US..."

How does one form a REGEX to detect multiple digits in a string? [duplicate]

This question already has answers here:
Extracting numbers from a string using regular expressions
(4 answers)
Closed 8 years ago.
I just learned about RegExp yesterday. I’m trying to figure something out: currently in a function I'm iterating through a string that's been split into an array to pull out and add up the numbers within it. There are examples like, 7boy20, 10, 2One, Number*1*, 7Yes9, Sir2, and 8pop2 which need to have the digits extracted.
So far, this only works to detect a single digit match:
var regexp = /(\d+)/g;
I've also tried:
var regexp =/(\d+)(\d?)/g;
...but it was to no avail.
UPDATE: This is the code I've been using, and am trying to fix as some have asked:
var str = "7boy20 10 2One Number*1* 7Yes9 Sir2 8pop2";
//var str = "7Yes9", "Sir2";
//var str = "7boy20";
function NumberAddition(str) {
input = str.split(" ");
var finalAddUp = 0;
var finalArr = [];
for(var i = 0; i<=input.length-1; i++) {
var currentItem = input[i];
var regexp = /(\d+)/g;
finalArr.push(currentItem.match(regexp));
var itemToBeCounted = +finalArr[i];
finalAddUp += itemToBeCounted;
}
console.log(finalArr);
return finalAddUp;
//OUTPUT ---> [ [ '7', '20' ], [ '10' ], [ '2' ], [ '1' ], [ '7', '9' ], [ '2' ], [ '8', '2' ] ] (finalArr)
//OUTPUT --->NaN (finalAddUp)
How would I turn that output into numbers I can add up?
Is this what you are looking for ?
This will give you every digit by them selves.
var re = /(\d)/g;
var str = '123asdad235 asd 23:"#&22 efwsg34t\nawefqreg568794';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
This will give you the numbers and not just the digits.
var re = /(\d+)/g;
var str = '123asdad235 asd 23:"#&22 efwsg34t\nawefqreg568794';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
Using the code from the last example m will be an array of all the numbers that you can SUM up using reduce Tho index 0 will always be the entire matched string, so skip that one...
m.reduce(function(previousValue, currentValue, index, array){
return index === 0 ? 0 : previousValue + currentValue;
});
To extract the numbers from the string, you can use one of these:
str.match(/\d+/g)
str.split(/\D+/)
And then, to sum the array, you can use
arr.reduce(function(a,b){ return +a + +b;}); // ES5
arr.reduce((a,b) => +a + +b); // ES6
Example:
"7boy20".split(/\D+/).reduce((a,b) => +a + +b); // Gives 27
Note that browser support for ES6 arrow functions is currently very small.
If you want a regex to match all digit:
var regDigit = /[^0-9.,]/g;
If you want a regex to match all letter:
var regString = /[^a-zA-Z.,]/g;
If you want to see the full JS code:
var s = ["7boy20", "10", "2One", "Number*1*", "7Yes9", "Sir2", , "8pop2"];
var regDigit = /[^0-9.,]/g;
var regString = /[^a-zA-Z.,]/g;
var extractDigit = s[0].replace(regDigit, '');
var extractString = s[0].replace(regString, '');
console.log("The extracted digit is " + extractDigit);
console.log("The extracted string is " + extractString);
Working Demo
To extract the digits, I would just replace the non-digits with nothing
var myregexp = /\D+/g;
result = subject.replace(myregexp, "");

Parse complex string with one regular expression

How can I get from this string
genre:+Drama,Comedy+cast:+Leonardo+DiCaprio,Cmelo+Hotentot+year:+1986-1990
this
genre: [Drama, Comedy],
cast: [Leonardo DiCaprio, Cmelo Hotentot],
year: [1986-1990]
with one regular expression?
This could be done using one regex and overload of replace function with replacer as a second argument. But honestly, I have to use one more replace to get rid of pluses (+) - I replaced them by a space () char:
var str = 'genre:+Drama,Comedy+cast:+Leonardo+DiCaprio,Cmelo+Hotentot+year:+1986-1990';
str = str.replace(/\+/g, ' ');
var result = str.replace(/(\w+:)(\s?)([\w,\s-]+?)(\s?)(?=\w+:|$)/g, function (m, m1, m2, m3, m4, o) {
return m1 + ' [' + m3.split(',').join(', ') + ']' + (o + m.length != str.length ? ',' : '') + '\n';
});
You could find the full example on jsfiddle.
You will not get them into arrays from the start, but it can be parsed if the order stays the same all the time.
var str = "genre:+Drama,Comedy+cast:+Leonardo+DiCaprio,Cmelo+Hotentot+year:+1986-1990";
str = str.replace(/\+/g," ");
//Get first groupings
var re = /genre:\s?(.+)\scast:\s?(.+)\syear:\s(.+)/
var parts = str.match(re)
//split to get them into an array
var genre = parts[1].split(",");
var cast = parts[2].split(",");
var years = parts[3];
console.log(genre);
You can't do this using only regular expressions cause you're trying to parse a (tiny) grammar.

Categories