Regex get all content between brackets - javascript

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('(?<=",)(.*)(?=])')

Related

How to use a variable in a match method with regular expression pattern

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)]

Check string starting with substring using regex

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.

replace parenthesis in javascript

How do you replace parenthesis with javascript.
I have a format like this:
(14.233,72.456),(12.4566,45.345),(12.456,13.567)
How can I get a format like given below:
14.233,72.456#12.4566,45.345#12.456,13.567
I have tried the following:
bounds = bounds.replace(/\)\,\(/g,'#');
bounds = bounds.replace(/\(/g,'');
bounds = bounds.replace(/\)/,'');
Splitting the string up by the delimiters and join them with your new delimiter:
var data = "(14.233,72.456),(12.4566,45.345),(12.456,13.567)";
data = data.slice(1, -1).split('),(').join('#');
Or using RegEx:
var data = "(14.233,72.456),(12.4566,45.345),(12.456,13.567)";
data = data.slice(1, -1).replace(/\),\(/g, '#');
You may try this (matches only float numbers) :
var s = '(14.233,72.456),(12.4566,45.345),(12.456,13.567)';
bounds = s.match(/\d+\.\d+,\d+\.\d+/g).join('#');
s.match(/\d+\.\d+,\d+\.\d+/g) returns :
['14.233,72.456', '12.4566,45.345', '12.456,13.567']
In addition, you might need to deal with an empty string :
bounds = (s.match(/\d+\.\d+,\d+\.\d+/g) || []).join('#');
var string = "(14.233,72.456),(12.4566,45.345),(12.456,13.567)";
var str = string.substring(1, string.length-1).split('),(').join('#');
alert(str);
Try this, which is almost the same as your code:
bounds = bounds.replace(/\),\(/g,'#').replace(/^\(|\)$/g,'');
See here the code working: http://jsfiddle.net/K8ECj/
[Edited to eliminate capture]
You can use .replace("(", "").replace(")", "");

How to get desired javascript string

I have a JavaScript string sentrptg2c#appqueue#sentrptg2c#vwemployees#
I want to get last part of the string: vwemployees through RegExp or from any JavaScript function.
and also want to remove that last keyword from string so that next time string will be like this sentrptg2c#appqueue#sentrptg2c#
I have tried
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var array = url.split('/');
var lastsegment = array[array.length-1];
and get vwemployees last segment but the string remains the same
sentrptg2c#appqueue#sentrptg2c#vwemployees#
It should be sentrptg2c#appqueue#sentrptg2c# when above code runs.
Please suggest a way to do this in JavaScript
JSFiddle: http://jsfiddle.net/satpalsingh/ykBCG/
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
//Assuming # as seperator
var array = str.split('#');
//Clear empty value in array
var newArray = array.filter(function(v){return v!==''});
var lastsegment = newArray[newArray.length-1];
alert(lastsegment);
//output is "vwemployees"
<script type="text/javascript">
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var arr = str.split("#");
alert(arr[arr.length-2]);
</script>
split function will do the job for you.
use split() , splice() to remove from array and join() to join them back again
var str="sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var reqvalue=str.split('#');
alert(reqvalue[3]);
reqvalue.splice(3,1);
alert(reqvalue.join('#'))
fiddle here
The split function can help you: http://www.w3schools.com/jsref/jsref_split.asp
yourString.split("#");
You will get an array with your values: sentrptg2c,appqueue,sentrptg2c,vwemployees
After that you just have to remove the last element, and rebuild your string from this array.
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
alert(str);
var arr = str.split('#');
var lastsegment = arr[arr.length-2];
alert(lastsegment);
var new_str = str.replace(lastsegment+'#', '');
alert(new_str);

get particular string part in javascript

I have a javascript string like "firstHalf_0_0_0" or secondHalf_0_0_0". Now I want to get the string before the string "Half" from above both strings using javascript.Please help me.
Thanks.
var myString = "firstHalf_0_0_0";
var parts = myString.split("Half");
var thePart = parts[0];
var str = 'firstHalf_0_0_0',
part = str.match(/(\w+)Half/)[1];
alert(part); // Alerts "first"
var str = "firstHalf.....";
var index = str.indexOf("Half");
var substring = str.substr(0, index);
jsFiddle demo.
Using this you can get any particular part of string.
var str= 'your string';
var result = str.split('_')[0];
Working example here for your particular case.
http://jsfiddle.net/7kypu/3/
cheers!

Categories

Resources