splitting a string with a decimal number and some characters [duplicate] - javascript

This question already has answers here:
Splitting a string at special character with JavaScript
(8 answers)
How do I split a string, breaking at a particular character?
(17 answers)
Closed 4 years ago.
I have strings like:
'1234picas'
'1234 px'
'145.4us'
I want to split them in two parts: the numeric part and the non numeric one. For example: '1234.4us' need to be splitted in '1234.4' and 'us'. I am tempted to insert a separator between the last digit and the non numeric and use split but is there a better way to do this in JavaScript
Thanks
Note: this is not the slitting of a string at special char. it could be converted to that but this is what I am trying to avoid.

You can do it using String.prototype.match():
const a = '1234picas';
const b = '1234 px';
const c = '145.4us';
function split(input) {
const splitArray = input.match(/([\d\.]+)(.*)/); // match only digits and decimal points in the first group and match the rest of the string in second group
return {
numeric: splitArray[1],
nonnumeric: splitArray[2],
};
}
console.log(split(a));
console.log(split(b));
console.log(split(c));
Regex explanation | Regex101

You can use .split with a regex using a lookahead:
str.split(/(?=[^\d.-])/g))
.map(y => [
y[0],
y.slice(1).join('').trim()
])
x = ["1234picas", "1234 px", "145.4us"];
console.log(x.map(y =>
y.split(/(?=[^\d.-])/g))
.map(y => [
y[0],
y.slice(1).join('').trim()
])
)

You can do like this in javascript to split:
var myString = '145.4us';
var splits = myString.split(/(\d+\.?\d+)/);
console.log(splits);

here's one way to do it using parseFloat() and slice() , you can add it to the Sting.prototype if you want :
const str1 = '1234picas',
str2 = '1234 px',
str3 = '145.4us';
String.prototype.split = function () {
const num = parseFloat(this);
const alph = this.slice(num.toString().length, this.length)
return {
num,
alph
}
}
console.log(str1.split());
console.log(str2.split());
console.log(str3.split());

This may help you:
var a = "4343.453fsdakfjdsa";
a.match(/[a-zA-Z]+|[\d\.?]+/ig);
MDN for String.match
It basically says match the alphabetical letters OR match numbers with an optional period. The ig is insensitive (which is not really needed) and global as in don't return on the first match, keep going until all of the string has been parsed.

Regex!
Here is how it works: https://regex101.com/r/XbI7Mq/1
const test = ['1234picas', '1234 px', '145.4us', 'no'];
const regex = /^(\d+\.?\d+)\s?(.*)/;
test.forEach(i => {
const result = regex.exec(i);
if (result) {
console.log(result[1], result[2])
}
});

Related

how to find the first number from string in js(javascript)? [duplicate]

This question already has answers here:
Get the first integers in a string with JavaScript
(5 answers)
Closed 6 months ago.
How to find the first number from string in javascript?
var string = "120-250";
var string = "120,250";
var string = "120 | 250";
Here is an example that may help you understand.
Use the search() method to get the index of the first number in the string.
The search method takes a regular expression and returns the index of the first match in the string.
const str = 'one 2 three 4'
const index = str.search(/[0-9]/);
console.log(index); // 4
const firstNum = Number(str[index]);
console.log(firstNum); // 2
Basic regular expression start of string followed by numbers /^\d+/
const getStart = str => str.match(/^\d+/)?.[0];
console.log(getStart("123,456"));
console.log(getStart("123-456"));
console.log(getStart("123|456"));
console.log(getStart("xxx,xxx"));
Or parseInt can be used, but it will drop leading zeros.
const getStart = str => parseInt(str, 10);
console.log(getStart("123,456"));
console.log(getStart("123-456"));
console.log(getStart("123|456"));
console.log(getStart("xxx,xxx"));

Getting second digit in a string using Javascript + Regex?

I'm wondering how I can get the second digit of a string where we don't know the number of digits the second number will be and without using splice or substring.
Ex. Channel.0.This.13
Should Return: 13
I've seen a few similar questions but they
typically know the number of digits the second number will be or
use splicing and substring, which I do not want to use in this case.
I appreciate the help :)
You could use String.prototype.match
In case that the string does not have any number, which matches will return null, you should use optional chaining ?. for a safer array index access
const str = "Channel.0.This.13";
const res = str.match(/\d+/g)?.[1];
console.log(res);
Use this regex (\d*)$. This will return only group with numbers which in the end of the string.
try this:
^[^\d]*\d+[^\d]+(\d+).*
Example:
const secondDigit = "Channel.0.This.13".match(/^[^\d]*\d+[^\d]+(\d+).*/).pop();
console.log(Number(secondDigit)); // 13
Assuming the original string contains only alphabets, numbers and '.' (in between),
Here is my solution (Pseudo code):
String givenString;
regex=/([0-9]+)(\.[a-zA-Z]+)?(\.[0-9]+)/;
//below code will return an array or null (if no second number is present)
match=givenString.match(regex);
//access last element of array. It will be like '.13' , just remove '.' and you are good to go
match.pop()
Javascript Regex Docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges
String.prototype.match() returns an array whose contents depend on the presence or absence of the global (g) flag, or null
const input1 = "Channel.0.This.13",
input2 = "Channel.0.This",
input3 = "Channel.This.";
const digitMatch = function (input) {
const digits = input.match(/\d+/g);
return (digits && digits[1]) || "Not Found";
};
console.log(digitMatch(input1));
console.log(digitMatch(input2));
console.log(digitMatch(input3));
if no matches are found.
It will help .*?\d+.*?(\d+).*$
"Channel.0.This.13.Channel.0.This.56".match(/.*?\d+.*?(\d+).*$/).pop()
// Output: 13
"Channel.0.This.13".match(/.*?\d+.*?(\d+).*$/).pop()
// Output: 13
You can reference the regex .match() key. str.match(reg)[1]
const str1 = 'Channel.0.This.13'
const str2 = 'some.otherStrin8..'
const str3 = '65 people.For.&*=20.them,98'
const regex = /\d+/g
function matchSecond(str, reg) {
str.match(reg)[1] ? output = str.match(reg)[1] : output = false
return output;
}
console.log(matchSecond(str1,regex))
console.log(matchSecond(str2,regex))
console.log(matchSecond(str3,regex))

Javascript split by numbers using regex

I'm trying to come up with a regex that will do following.
I have a string
var input_string = "E100T10P200E3000T3S10";
var output=input_string.split(**Trying to find this**);
this should give an array with all the letters in order with repetitions
output = ["E","T","P","E","T","S"]
See below. \d+ means one or more digits; filter (x => x) removes empty strings that can appear in the beginning or the end of the array if the input string begins or ends with digits.
var input_string = "E100T10P200E3000T3S10";
var output = input_string.split (/\d+/).filter (x => x);
console.log (output);
We can try just matching for capital letters here:
var input_string = "E100T10P200E3000T3S10";
var output = input_string.match(/[A-Z]/g);
console.log(output);
Another approach is spread the string to array and use isNaN as filter callback
var input_string = "E100T10P200E3000T3S10";
var output = [...input_string].filter(isNaN);
console.log(output);
You can use regex replace method. First replace all the digits with empty string and then split the resultant string.
const input_string = 'E100T10P200E3000T3S10';
const ret = input_string.replace(/\d/g, '').split('');
console.log(ret);

How to replace multiple strings with other multiple strings at a time in javascript? [duplicate]

This question already has answers here:
Replace multiple strings with multiple other strings
(27 answers)
Closed 3 years ago.
I have a string prototype whose code is given below:
String.prototype.replaceAll = function(str1, str2, ignore) {
return this.replace(
new RegExp(
str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"
):str2
)};
Usage:
var a = "I am Javascript";
console.log(
a.replaceAll("am", "love")
); // => I love Javascript
But when it comes to multiple exchange of characters or words, I have to run the prototype multiple times to achieve it. But I have thought of something like this:
var a = "I am Java";
console.log(
a.replaceAll(["am" , "Java"], ["love", "Javascript"])
); // => I love Javascript
So can you help me to achieve it? Or there is any other alternative?
I'd prefer to store replacements as key-value pairs in an object or as an array of pairs. Regardless of the format, you can dynamically create a regex by joining the values you want to replace using | alternation. Then give replace a callback function and use its match parameter as a key to look up its corresponding pair in the swaps object.
const s = "I am Java";
const swaps = {am: "love", Java: "JS"};
const pattern = new RegExp(Object.keys(swaps).join("|"), "g");
console.log(s.replace(pattern, m => swaps[m]));
To handle case-insensitive replacements, ensure all keys in swaps are lowercase (either programmatically or manually, depending on usage) and lowercase the matches before keying in:
const s = "I am Java";
const swaps = {am: "love", java: "JS"};
const pattern = new RegExp(Object.keys(swaps).join("|"), "gi");
console.log(s.replace(pattern, m => swaps[m.toLowerCase()]));
This works.
String.prototype.replaceAll = function(str1, str2, ignore) {
let flags = 'g';
if (ignore) {
flags += 'i';
}
if (Array.isArray(str1) && Array.isArray(str2)) {
let newStr = this;
str1.map((element, index) => {
if (str2[index]) {
newStr = newStr.replace(new RegExp(element, flags), str2[index]);
}
return newStr;
});
return newStr;
}
else {
return this.replace(new RegExp(str1, flags), str2);
}
}

JavaScript Split with RegEx without Global Match

I have an expression.
var expression = "Q101='You will have an answer here like a string for instance.'"
I have a regular expression that searches the expression.
var regEx = new regExp(/=|<>|like/)
I want to split the expression using the regular expression.
var result = expression.split(regExp)
This will return the following:
["Q101", "'You will have an answer here ", " a string for instance'"]
This is not what I want.
I should have:
["Q101", "'You will have an answer here like a string for instance'"]
How do I use the regular expression above to split only on the first match?
Since you only want to grab the two parts either side of the first delimiter it might be easier to use String.match and discard the whole match:
var expression = "Q101='You will have an answer here like a string for instance.'";
var parts = expression.match(/^(.*?)(?:=|<>|like)(.*)$/);
parts.shift();
console.log(parts);
expression = "Q101like'This answer uses like twice'";
parts = expression.match(/^(.*?)(?:=|<>|like)(.*)$/);
parts.shift();
console.log(parts);
JavaScript's split method won't quite do what you want, because it will either split on all matches, or stop after N matches. You need an extra step to find the first match, then split once by the first match using a custom function:
function splitMatch(string, match) {
var splitString = match[0];
var result = [
expression.slice(0, match.index),
expression.slice(match.index + splitString.length)
];
return result;
}
var expression = "Q101='You will have an answer here like a string for instance.'"
var regEx = new RegExp(/=|<>|like/)
var match = regEx.exec(expression)
if (match) {
var result = splitMatch(expression, match);
console.log(result);
}
While JavaScript's split method does have an optional limit parameter, it simply discards the parts of the result that make it too long (unlike, e.g. Python's split). To do this in JS, you'll need to split it manually, considering the length of the match —
const exp = "Q101='You will have an answer here like a string for instance.'"
const splitRxp = /=|<>|like/
const splitPos = exp.search(splitRxp)
const splitStr = exp.match(splitRxp)[0]
const result = splitPos != -1 ? (
[
exp.substring(0, splitPos),
exp.substring(splitPos + splitStr.length),
]
) : (
null
);
console.log(result)

Categories

Resources