I need some help with regular expressions in javascript. I've got a string like:
var S = '["abc","defg", "hij"]';
How could I split it in javascript to get a[0]=abc, a[1]=defg, a[2]=hij?
Because var a = S.split(','); just give me a[0]=["abc" and so on.
Thank you very much.
If you fix the quotes you use to delimit the string, then you can JSON.parse the string to an array and work with it as you need, like this:
var s = '["abc","defg", "hij"]';
var arr = JSON.parse(s);
console.log(arr);
console.log(arr[0]); // = 'abc'
If you mean:
var S = ["abc", "def", "ghi"];
Then use S[0], S[1] and S[2].
If you mean:
var S = "[\"abc\", \"def\", \"ghi\"]";
Then use JSON parser
Complete example:
var S = "[\"abc\", \"def\", \"ghi\"]";
var SParsed = JSON.parse(S);
alert(SParsed [1]); //def
Related
Hello i've this string ["type",[129,167,85,83]] that i want to extract only :
[129,167,85,83] using regexpr
I tried with the following :
var re = new RegExp('",(.*)]');
var r = '["type",[129,167,85,83]]'.match(re);
if (r)
console.log(r);
But this gives me the following result :
",[129,167,85,83]]
please how could i fix that ?
Not necessarily the best solution, but the quickest from where you are now. Match produces an array - you want the second item:
var re = new RegExp('",(.*)]');
var r = '["type",[129,167,85,83]]'.match(re);
if (r) console.log(r[1])
Here you go.
the trick was that adding (?<=,) will execlude comma.
Added a test below, see for your self
var regex = /(?<=,)(\[.*?\])/g;
var json = '["type",[129,167,85,83]]';
var r = json.match(regex);
console.log(r);
You can use JSON.parse
let str='["type",[129,167,85,83]]';
let arr=JSON.parse(str);
arr.shift();
let new_str=JSON.stringify(arr.flat());
console.log(new_str);
You can .split() characters followed by [ and closing ], get element at index 1
let str = `["type",[129,167,85,83]]`;
let [,match] = str.split(/.(?=\[)|\]$/);
console.log(match);
Probably best to use JSON.parse.
I have made a little example for you below;
var course = '["type",[129,167,85,83]]';
var resultArray = JSON.parse(course);
console.log(resultArray[1]); // 129,167,85,83
try this
var re = new RegExp('(?<=",)(.*)(?=])')
I want to get an array in JavaScript from a string, cutting it in half.
Example:
// From this:
var myStr = 'cocacola';
// To this:
var myArray = ['coca', 'cola'];
I tried the following method:
var myStr = 'cocacola';
var strHalf = myStr.length / 2;
// This won't work
var myArray = myStr.match(/.{1,strHalf}/g);
// Only this will work fine
var myArray = myStr.match(/.{1,4}/g);
You can do String.slice() to solve this
var myStr = 'cocacola';
let len = myStr.length;
let result = [myStr.slice(0, len/2), myStr.slice(len/2)]
console.log(result);
You'll need to to use the RegExp() constructor and make a string that it understands:
var regexString = "/.{1," + strHalf + "}/g";
var myRegex = new RegExp( regexString );
var myArray = myStr.match( myRegex );
...but be careful doing this; if strHalf is a string containing special characters like / then your RegExp will have weird behaviour.
You can create a non-hardcoded regexp by using the RegExp constructor:
var myArray = myStr.match(new RegExp('/.{1,'+strHalf+'}/g'));
The constructor has no clue that strHalf should be an integer, so make sure you can control that.
This is known to introduce a lot of security issues, please don't use this in production. Regexes are too often used when they shouldn't. If you ever use a regex, do look into other options
There are much better alternatives, but at least it's possible!
You dont need regex for that.
The easiest way is that:
var myStr = 'cocacola';
var strHalf = myStr.length / 2;
var array = [myStr.substr(0, strHalf),myStr.substr(strHalf, myStr.length)];
jsfiddle: https://jsfiddle.net/cudg8qc3/
You can just slice the string and place the first element in the first slot, and the second element in the second slot in the array.
var str_len = myStr.length
var my_array = [myStr.slice(0, str_len/2), myStr.slice(str_len/2, str_len)]
datastatusMonthly[0] - This is my String in javascript
If i print this, it is printing as same string.
How do i get the value of '0' index in array datastatusMonthly using this above string?
Any help please?
You can use eval. The eval function will evaluate your string. JS bin here https://jsbin.com/guqoqukoqa/edit?js,console
Solution without eval, which is evil, using regex with group:
var datastatusMonthly = [3];
var text = 'datastatusMonthly[0]';
var regex = /(datastatusMonthly)\[([0-9]+)\]/g;
var match = regex.exec(text);
var arrayName = match[1];
var arrayIndex = match[2];
console.log(window[arrayName][arrayIndex]);
This dose't have to be in a String i guess. correct me if i am not understanding it properly
var fistElement = datastatusMonthly[0];
This link might help https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Accessing_array_elements
I am writing js code to get array of elements after splitting using regular expression.
var data = "ABCXYZ88";
var regexp = "([A-Z]{3})([A-Z]{3}d{2})";
console.log(data.split(regexp));
It returns
[ 'ABCXYZ88' ]
But I am expecting something like
['ABC','XYZ','88']
Any thoughts?
I fixed your regex, then matched it against your string and extracted the relevant capturing groups:
var regex = /([A-Z]{3})([A-Z]{3})(\d{2})/g;
var str = 'ABCXYZ88';
let m = regex.exec(str);
if (m !== null) {
console.log(m.slice(1)); // prints ["ABC", "XYZ", "88"]
}
In your case, I don't think you can split using a regex as you were trying, as there don't seem to be any delimiting characters to match against. For this to work, you'd have to have a string like 'ABC|XYZ|88'; then you could do 'ABC|XYZ|88'.split(/\|/g). (Of course, you wouldn't use a regex for such a simple case.)
Your regexp is not a RegExp object but a string.
Your capturing groups are not correct.
String.prototype.split() is not the function you need. What split() does:
var myString = 'Hello World. How are you doing?';
var splits = myString.split(' ', 3);
console.log(splits); // ["Hello", "World.", "How"]
What you need:
var data = 'ABCXYZ88';
var regexp = /^([A-Z]{3})([A-Z]{3})(\d{2})$/;
var match = data.match(regexp);
console.log(match.slice(1)); // ["ABC", "XYZ", "88"]
Try this. I hope this is what you are looking for.
var reg = data.match(/^([A-Z]{3})([A-Z]{3})(\d{2})$/).slice(1);
https://jsfiddle.net/m5pgpkje/1/
Trying to check if randomString starting with just. (including the dot).
This should give me false but it's not the case:
var randomString = 'justanother.string';
var a = randomString.match('^just\.');
console.log(a);
I probably missed something in the regex argument.
You need to use create a Regular Expression and the use .test() method.
var randomString = 'justanother.string';
var a = /^just\./.test(randomString)
console.log(a);
The answer is simple, you didn't create regex propertly.
'this is not regex'
/this is regex/
new RexExp('this is also regex')
var randomString = 'justanother.string';
var a = randomString.match(/^just\./);
console.log(a);
// I sugest dooing something like this
const startsWithJust = (string) => /^just\./.test(string)
var randomString = 'justanother.string';
var another = 'just.....................';
console.log( randomString.match('^(just[.]).*') );
console.log( another.match('^just[.].*') );
If you wish to keep your lines the same only one change is needed.
var a = randomString.match('^just\\.');
you need to escape the first backslash.