Given the following patterns:
"profile[foreclosure_defenses_attributes][0][some_text]"
"something[something_else_attributes][0][hello_attributes][0][other_stuff]"
I am able to extract the last part using non-capturing groups:
var regex = /(?:\w+(\[\w+\]\[\d+\])+)(\[\w+\])/;
str = "profile[foreclosure_defenses_attributes][0][properties_attributes][0][other_stuff]";
match = regex.exec(str);
["profile[foreclosure_defenses_attributes][0][properties_attributes][0][other_stuff]", "[properties_attributes][0]", "[other_stuff]"]
However, I want to be able to get everything but the last part. In other words, everything but [some_text] or [other_stuff].
I cannot figure out how to do this with noncapturing groups. How else can I achieve this?
Something like?
shorter, and matches from the back if you can have more of the [] items.
var regex = /(.*)(?:\[\w+\])$/;
var a = "something[something_else_attributes][0][hello_attributes][0][other_stuff11][other_stuff22][other_stuff33][other_stuff44]".match(regex)[1];
a;
or using replace, though less performant.
var regex = /(.*)(?:\[\w+\])$/;
var a = "something[something_else_attributes][0][hello_attributes][0][other_stuff11][other_stuff22][other_stuff33][other_stuff44]".replace(regex, function(_,$1){ return $1});
a;
If those really are your strings:
var regex = /(.*)\[/;
Related
I am looking for a regex that will match the first line, but not the second. This is what I have /^github.com\/[^\\\n]+$/
github.com/reggi
github.com/reggi/example
https://regexr.com/3ld7o
var patternA = /^github.com\/[^\\\n]+$/
var patternB = /^github\.com\/.+/
var patternC = /^github.com\/[^\/\n]+$/
var examples = function (pattern) {
return [
!!'github.com/reggi/genesis/soup'.match(pattern),
!!'github.com/reggi/genesis'.match(pattern),
!!'github.com/reggi'.match(pattern),
]
}
console.log(examples(patternA))
console.log(examples(patternB))
console.log(examples(patternC))
^github.com\/[^\/\n]+$
I think you just had the wrong type of slash escaped.
https://regexr.com/3ld8v
The pattern /^github\.com\/.+/ is enough for your need (remember to uncheck m - multiline when you test with regexr.com).
https://regexr.com/3ld7u
Suppose I have a sting like this: ABC5DEF/G or it might be ABC5DEF-15 or even just ABC5DEF, it could be shorter AB7F, or AB7FG/H.
I need to create a javascript variable that contains the substring only up to the '/' or the '-'. I would really like to use an array of values to break at. I thought maybe to try something like this.
...
var srcMark = array( '/', '-' );
var whereAt = new RegExp(srcMark.join('|')).test.str;
alert("whereAt= "+whereAt);
...
But this returns an error: ReferenceError: Can't find variable: array
I suspect I'm defining my array incorrectly but trying a number of other things I've been no more successful.
What am I doing wrong?
Arrays aren't defined like that in JavaScript, the easiest way to define it would be with:
var srcMark = ['/','-'];
Additionally, test is a function so it must be called as such:
whereAt = new RegExp(srcMark.join('|')).test(str);
Note that test won't actually tell you where, as your variable suggests, it will return true or false. If you want to find where the character is, use String.prototype.search:
str.search(new RegExp(srcMark.join('|'));
Hope that helps.
You need to use the split method:
var srcMark = Array.join(['-','/'],'|'); // "-|/" or
var regEx = new RegExp(srcMark,'g'); // /-|\//g
var substring = "222-22".split(regEx)[0] // "222"
"ABC5DEF/G".split(regEx)[0] // "ABC5DEF"
From whatever i could understand from your question, using this RegExp /[/-]/ in split() function will work.
EDIT:
For splitting the string at all special characters you can use new RegExp(/[^a-zA-Z0-9]/) in split() function.
var arr = "ABC5DEF/G";
var ans = arr.split(/[/-]/);
console.log(ans[0]);
arr = "ABC5DEF-15";
ans = arr.split(/[/-]/);
console.log(ans[0]);
// For all special characters
arr = "AB7FG/H";
ans = arr.split(new RegExp(/[^a-zA-Z0-9]/));
console.log(ans[0]);
You can use regex with String.split.
It will look something like that:
var result = ['ABC5DEF/G',
'ABC5DEF-15',
'ABC5DEF',
'AB7F',
'AB7FG/H'
].map((item) => item.split(/\W+/));
console.log(result);
That will create an Array with all the parts of the string, so each item[0] will contain the text till the / or - or nothing.
If you want the position of the special character (non-alpha-numeric) you can use a Regular Expression that matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_], that is: \W
var pattern = /\W/;
var text = 'ABC5DEF/G';
var match = pattern.exec(text);
var position = match.index;
console.log('character: ', match[0]);
console.log('position: ', position);
I need to extract an id from a string but I can't only the ID. I'm trying to user a pattern that works fine in Java, but in JS it yields more results than I like. Here is my code:
var reg = new RegExp("&topic=([0-9]+)");
When applying execute this against the string "#p=activity-feed&topic=1697"
var results = reg.exec("#p=activity-feed&topic=1697");
I was hoping to get just the number part (1697, in this case) because this was preceded by "&topic=", but this is returning two matches:
0: "&topic=1697"
1: "1697"
Can someone help me to get ["1967","9999"] from the string "#p=activity-feed&topic=1697&no_match=1111&topic=9999"?
Assuming the browser support is right for your use case, URLSearchParams can do all of the parsing for you:
var params = new URLSearchParams('p=activity-feed&topic=1697&no_match=1111&topic=9999');
console.log(params.getAll('topic'));
While Noah's answer is arguably more robust and flexible, here's a regex-based solution:
var topicRegex = /&topic=(\d+)/g; // note the g flag
var results = [];
var testString = "p=activity-feed&topic=1697&no_match=1111&topic=9999";
var match;
while (match = reg.exec(testString)) {
results.push(match[1]); // indexing at 1 pulls capture result
}
console.log(results); // ["1697", "9999"]
Works for any arbitrary number of matches or position(s) in the string. Note that the matches are still strings, if you want to treat them as numbers you'll have to do something like:
var numberized = results.map(Number);
where do we start if we want to remove the affix from this sentence meangan menangkan dimenangkan
affix_list = [
'me-an',
'me-kan,
'di-kan
]
string = 'meangan menangkan dimenangkan'
so it will output
output = [
'ang',
'nang'
'menang'
]
You might want to use regular expressions for those replacements. Starting from your affix_list, this should work:
output = affix_list.reduce(function(str, affix) {
var parts = affix.split("-");
var regex = new RegExp("\\b"+parts[0]+"(\\S+)"+parts[1]+"\\b", "g");
return str.replace(regex, "$1")
}, string).split(" ");
Your regexes will look like this:
/\bme(\S+)an\b/g
/\bme(\S+)kan\b/g
/\bdi(\S+)kan\b/g
But note that you will of course need to replace me-kan before me-an, else "menangkan" will become nangk before the me-kan expression can be applied.
You'll need to start with Javascript regular expressions and iterate through the values, retrieving the middle value accordingly. I'll do that first one for you, and you can try out the rest :)
var re = /me(\w+)an/;
var str = "meangan";
var newstr = str.replace(re, "$1");
console.log(newstr);
// outputs ang
Reference: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
I would like to split characters into array using javascript with regex
foo=foobar=&foobar1=foobar2=
into
foo, foobar=,
foobar1, foobar2=
Sorry for not being clear, let me re describe the scenario.
First i would split it by "&" and want to post process it later.
str=foo=foobar=&foobar1=foobar2=
var inputvars=str.split("&")
for(i=0;i<inputvars.length;i++){
var param = inputvars[i].split("=");
console.log(param);
}
returns
[foo,foobar]
[]
[foobar1=foobar2]
[]
I tried to use .split("=") but foobar= got splited out as foobar.
I essentially want it to be
[foo,foobar=]
[foobar1,foobar2=]
Any help with using javascript to split first occurence of = only?
/^([^=]*)=(.*)/.exec('foo=foobar=&foobar1=foobar2=')
or simpler to write but using the newer "lazy" operator:
/(.*?)=(.*)/.exec('foo=foobar=&foobar1=foobar2=')
from malvolio, i got to conclusion below
var str = 'foo=foobar=&foobar1=foobar2=';
var inputvars = str.split("&");
var pattern = /^([^=]*)=(.*)/;
for (counter=0; counter<inputvars.length; counter++){
var param = pattern.exec(inputvars[counter]);
console.log(param)
}
and results (which is what i intended)
[foo,foobar=]
[foobar1,foobar2=]
Thanks to #malvolio hint of regex
Cheers