I want to parse this statement in javascript
["TWA"]["STEL"]
and get TWA, STEL value. I guess this is a json and use JSON.parse() method but doesn't work.
That is not a JSON, but you can easily parse it with the pattern matcher:
https://jsfiddle.net/60dshj3x/
let text = '["TWA"]["STEL"]'
let results = text.match(/\["(.*)"\]\["(.*)"]/)
// note that results[0] is always the entire string!
let first = results[1]
let second = results[2]
console.log("First: " + first + "\nSecond: " + second);
If it is a string then a simple regex will do the trick.
const regex = /\["(\w+)"\]/gm;
const str = `["TWA"]["STEL"]`;
let m;
let words = [];
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
if(groupIndex===1)words.push(match)
});
}
console.log(words.join(','))
Related
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:
My string have a two part and separated by /
I want left side string of slash accept any string except "HAHAHA" end of word
And right side string of slash accept any string and allow use "HAHAHA" in end of string
only by Regular Expression and match function to return result parts
For example:
Accept : fooo/baarHAHAHA
Reject : fooHAHAHA/baaar
I want if string have one part, for example baarHAHAHA, accept but result like this:
string: baarHAHAHA
Group1: empty
Group2: baarHAHAHA
Have any idea?
You can try
^(\w*?)(?<!HAHAHA)\/?(\w+)$
Explanation of the above regex:
^, $ - Represents start and end of the line respectively.
(\w*?) - Represents first capturing group capturing the word characters([a-zA-Z0-9_]) zero or more times lazily.
(?<!HAHAHA) - Represents a negative look-behind not matching if the first captured group contains HAHAHA at the end.
\/? - Matches / literally zero or one time.
(\w+) - Represents second capturing group matching word characters([0-9a-zA-Z_]) one or more times.
You can find the demo of the above regex in here.
const regex = /^(\w*?)(?<!HAHAHA)\/?(\w+)$/gm;
const str = `
fooo/baarHAHAHA
fooHAHAHA/baaar
/baar
barHAHAHA
`;
let m;
let resultString = "";
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
if(m[1] === "")resultString = resultString.concat(`GROUP 1: empty\nGROUP 2: ${m[2]}\n`);
else resultString = resultString.concat(`GROUP 1: ${m[1]}\nGROUP 2: ${m[2]}\n`);
}
console.log(resultString);
You don't need regex for this, which is good since it is quite slow. A simple string.split() should be enough to separate the parts. Then you can just check if the word contains "HAHAHA" with the string.endsWith() method.
const a = 'fooHAHAHA/bar';
const b = 'foo/bar';
const c = 'fooHAHAHA';
console.log(a.split('/')); // Array [ 'fooHAHAHA', 'bar' ]
console.log(b.split('/')); // Array [ 'foo', 'bar' ]
console.log(c.split('/')); // Array [ 'fooHAHAHA' ]
// therefore ...
function splitMyString(str) {
const strSplit = str.split('/');
if (strSplit.length > 1) {
if (strSplit[0].endsWith('HAHAHA')) {
return ''; // or whatever you want to do if it gets rejected ...
}
}
return str;
}
console.log('a: ', splitMyString(a)); // ''
console.log('b: ', splitMyString(b)); // foo/bar
console.log('c: ', splitMyString(c)); // fooHAHAHA
Alternative non-regex solution:
const a = 'fooHAHAHA/bar';
const b = 'foo/bar';
const c = 'fooHAHAHA';
function splitMyString(str) {
const separator = str.indexOf('/');
if (separator !== -1) {
const firstPart = str.substring(0, separator);
if (firstPart.endsWith('HAHAHA')) {
return ''; // or whatever you want to do if it gets rejected ...
}
}
return str;
}
console.log('a: ', splitMyString(a)); // ''
console.log('b: ', splitMyString(b)); // foo/bar
console.log('c: ', splitMyString(c)); // fooHAHAHA
var str, re;
function match(rgx, str) {
this.str = str;
this.patt = rgx
var R = [], r;
while (r = re.exec(str)) {
R.push({
"match": r[0],
"groups": r.slice(1)
})
}
return R;
}
str = `
fooo/baarHAHAHA
fooHAHAHA/baaar
/baar
barHAHAHA
barr/bhHAHAHA
`;
re = /(?<=\s|^)(.*?)\/(.*?HAHAHA)(?=\s)/g;
console.log(match(re, str))
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Edit: When I make this code I think to letting user to call the str and when call it, it will return the mactheds and groups. But, if I make like this.str = str and have return too, this.str will be declined.
I created this regex: /[::].+[^\>]/g
Test:
let str = "<foo::bar>"
let match = str.match(/[::].+[^\>]/g).join('')
console.log(match)
Expected answer : bar
Actual answer : ::bar
Answers appreciated.
One option is to use a lookbehind assertion ((?<=)), which is currently supported only by Chrome & Safari:
const str = "<foo::bar>"
const match = str.match(/(?<=::)[^\>]+/g).join('')
console.log(match)
Another option is to use a capturing group instead of a lookbehind:
::([^>]+)
Regex demo
For example
const regex = /::([^>]+)/g;
const str = `<foo::bar>`;
let m;
let match = [];
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
match.push(m[1]);
}
console.log(match.join(''));
If you want to match the whole pattern of the string, you might use:
<[^>]+::([^>]+)>
Regex demo
const regex = /<[^>]+::([^>]+)>/g;
const str = `<foo::bar>`;
let m;
let match = [];
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
match.push(m[1]);
}
console.log(match.join(''));
Adding an extra match & join to remove '::' had solved the problem.
Working code:
let str = "<foo::bar>"
let match = str.match(/[::].+[^\>]/g).join('')
.match(/[^(::)].+/g).join()
console.log(match)
I have a series of varying strings which I need to turn into arrays on every second occurrence of \n, for simplicity please consider the next example:
const str = 'banana\napple\nmango\n3.5'
//I have tried and failed with:
const arr = str.split(/(^\n)+\n(^\n)+/)
// Result should be:
// const arr = ['banana\napple', 'mango\n3.5']
Do I have to use a loop here or what?
You could take match instead of split by taking some non breaking character, a breaking character and other non breking character.
const
string = 'banana\napple\nmango\n3.5',
result = string.match(/[^\n]+\n[^\n]+/g);
console.log(result);
Damn this is an ugly approach:
let t1 = performance.now();
const result = 'banana\napple\nmango\n3.5'
.split('\n')
.map((str, i, arr) => (i % 2) === 0 ? str + '\n' + arr[i+1] : null )
.filter((str) => str !== null);
let t2 = performance.now();
console.log(result, t2-t1 + 'μs');
I need to remove substrings containing the word "page=" followed by number.
Ex.
s= "aaaapage=500";
Should be
s = "page=500"
I tried
s = s.replace(/&page=\d/g,"");
and
s = s.replace(/&page=[\d]+/g,"");
to no avail
You can match text before and after while capturing the page=[digits]:
s= "aaaapage=500";
document.write(s.replace(/.*(page=\d+).*/, '$1') + "<br/>");
// or with multiline input
s= "a\na\naapage=500text\nnewline";
document.write(s.replace(/[\s\S]*(page=\d+)[\s\S]*/, '$1'));
This is good when we only have 1 page=[digits].
When we have more, use exec:
var re = /page=\d+/g;
var str = 'apageaaaapage=500apageaaaapage=210';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
document.write(m[0] + "<br/>");
}
I just realized
s = s.replace(/&page=[\d]+/g,"");
actually works
Just remove all the word chars which exists before page=
s.replace(/\w*(page=\d+)/g,"$1");