I need a way to match a word against a string and not get false positives. Let me give an example of what I mean:
"/thing" should match the string "/a/thing"
"/thing" should match the string "/a/thing/that/is/here"
"/thing" should NOT match the string "/a/thing_foo"
Basically, it should match if the exact characters are there in the first string and the second, but not if there are run-ons in the second (such as an underscore like in thing_foo).
Right now, I'm doing this, which is not working.
let found = b.includes(a); // true
Hopefully my question is clear enough. Thanks for the help!
Boy did this turn in to a classic XY Problem.
If I had to guess, you want to know if a path contains a particular segment.
In that case, split the string on a positive lookahead for '/' and use Array.prototype.includes()
const paths = ["/a/thing", "/a/thing/that/is/here", "/a/thing_foo"]
const search = '/thing'
paths.forEach(path => {
const segments = path.split(/(?=\/)/)
console.log('segments', segments)
console.info(path, ':', segments.includes(search))
})
Using the positive lookahead expression /(?=\/)/ allows us to split the string on / whilst maintaining the / prefix in each segment.
Alternatively, if you're still super keen in using a straight regex solution, you'll want something like this
const paths = ["/a/thing", "/a/thing/that/is/here", "/a/thing_foo", "/a/thing-that/is/here"]
const search = '/thing'
const rx = new RegExp(search + '\\b') // note the escaped backslash
paths.forEach(path => {
console.info(path, ':', rx.test(path))
})
Note that this will return false positives if the search string is followed by a hyphen or tilde as those are considered to be word boundaries. You would need a more complex pattern and I think the first solution handles these cases better.
I'd recommend using regular expressions...
e.g. The following regular expression /\/thing$/ - matches anything that ends with /thing.
console.log(/\/thing$/.test('/a/thing')) // true
console.log(/\/thing$/.test('/a/thing_foo')) // false
Update: To use a variable...
var search = '/thing'
console.log(new RegExp(search + '$').test('/a/thing')) // true
console.log(new RegExp(search + '$').test('/a/thing_foo')) // false
Simply with following regex you can do it
var a = "/a/thing";
var b = "/a/thing/that/is/here";
var c = "/a/thing_foo";
var pattern = new RegExp(/(:?(thing)(([^_])|$))/);
pattern.test(a) // true
pattern.test(b) // true
pattern.test(c) // false
Related
Currently have the following regex to capture all content within square brackets:
regex = /[^[\]]+(?=])/g
Meaning that:
string = "[Foo: Bar] [Biz: Baz]"
string.match(regex)
In JavaScript will return: ["Foo: Bar", "Biz: Baz"]
for a next step, I want to only get the text that follows a the colon. It is safe to assume that on all matches, we'll consistently have a return where each string in the return array matches the above pattern.
I'm sure there's some way to extend my regex to do this at the same time as finding the text within square brackets, but I'm just not sure how to do so. I've tried using some positive look-aheads, but I have no idea where to add them.
Another simple way:
const regex = /\[(\w+)\s*:\s*(\w+)\]/g;
const string = "[Foo: Bar] [Biz: Baz]";
let match;
while(match = regex.exec(string)){
console.log(`Pro: ${match[1]}`)
console.log(`Val: ${match[2]}`)
}
You can add :) or (: ) if you need also to match the space after the colon):
var string = "[Foo: Bar] [Biz: Baz]"
var regex = /[^[\]:]+(?=])/g;
console.log(string.match(regex));
You can try something like this
\[([^:]+:\s*)([^\]]+)
let regex = /\[([^:]+:\s*)([^\]]+)\]/g
let arr = []
let string = "[Foo: Bar] [Biz: Baz]"
while((arr =regex.exec(string))!== null){
console.log(`key -> ${arr[1]}`)
console.log(`val -> ${arr[2]}`)
}
I'm working with a string where I need to extract the first n characters up to where numbers begin. What would be the best way to do this as sometimes the string starts with a number: 7EUSA8889er898 I would need to extract 7EUSA But other string examples would be SWFX74849948, I would need to extract SWFX from that string.
Not sure how to do this with regex my limited knowledge is blocking me at this point:
^(\w{4}) that just gets me the first four characters but I don't really have a stopping point as sometimes the string could be somelongstring292894830982 which would require me to get somelongstring
Using \w will match a word character which includes characters and digits and an underscore.
You could match an optional digit [0-9]? from the start of the string ^and then match 1+ times A-Za-z
^[0-9]?[A-Za-z]+
Regex demo
const regex = /^[0-9]?[A-Za-z]+/;
[
"7EUSA8889er898",
"somelongstring292894830982",
"SWFX74849948"
].forEach(s => console.log(s.match(regex)[0]));
Can use this regex code:
(^\d+?[a-zA-Z]+)|(^\d+|[a-zA-Z]+)
I try with exmaple and good worked:
1- somelongstring292894830982 -> somelongstring
2- 7sdfsdf5456 -> 7sdfsdf
3- 875werwer54556 -> 875werwer
If you want to create function where the RegExp is parametrized by n parameter, this would be
function getStr(str,n) {
var pattern = "\\d?\\w{0,"+n+"}";
var reg = new RegExp(pattern);
var result = reg.exec(str);
if(result[0]) return result[0].substr(0,n);
}
There are answers to this but here is another way to do it.
var string1 = '7EUSA8889er898';
var string2 = 'SWFX74849948';
var Extract = function (args) {
var C = args.split(''); // Split string in array
var NI = []; // Store indexes of all numbers
// Loop through list -> if char is a number add its index
C.map(function (I) { return /^\d+$/.test(I) === true ? NI.push(C.indexOf(I)) : ''; });
// Get the items between the first and second occurence of a number
return C.slice(NI[0] === 0 ? NI[0] + 1 : 0, NI[1]).join('');
};
console.log(Extract(string1));
console.log(Extract(string2));
Output
EUSA
SWFX7
Since it's hard to tell what you are trying to match, I'd go with a general regex
^\d?\D+(?=\d)
I am trying to make ifcondition for a large number of chars.
I can use
if (str==!||str==#||str==#||str==$||str==^||str==&)
And so on, but this seems very inefficient. I would like to get the condition to work if the char is on of those:
!##%$^&()_-+=\?/.,'][{}<>`~
Is there is any shorter and more efficient way of doing it?
for (var c0 = 1; c0 > fn.length++; c0++) {
var str = fn.charAt(c0--);
if (str ==-"!##%$^&()_-+=\?/.,'][{}<>`~") {
}
}
I want the check to accrue on every single char from the string above.
You can use a regular expression character class to check if your character matches a particular character:
/^[\!##%$\^&\(\)_\-\+=\?\/\.,'\]\[\{\}\<\>`~]$/
Here I have escape special characters so that they get treated like regular characters.
See working example below:
const regex = /^[\!##%$\^&\(\)_\-\+=\?\/\.,'\]\[\{\}\<\>`~]$/,
charA = '#', // appears in char set
charB = 'A'; // doesn't appear in char set
console.log(regex.test(charA)); // true
console.log(regex.test(charB)); // false
Alternatively, if you don't want to use regular expressions you can instead put all your characters into an array and use .includes to check if your character is in your array.
const chars = "!##%$^&()_-+=\?/.,'][{}<>`~",
charArr = [...chars],
charA = '#', // is in char set
charB = 'A'; // isn't in char set
console.log(charArr.includes(charA)); // true
console.log(charArr.includes(charB)); // false
Just use regular expressions rather than manual single character checking.
const pattern = new RegExp("!##%$^&()_-+=\?\/.,'][{}<>`~");
const exists = pattern.test(str);
if (exists) {
// code logic for special character exists in string
}
First you can use split('') to split a string into an array of characters. Next you can use .some to check if a condition is true for at least one element in the array:
"!##%$^&()_-+=\?/.,'][{}<>`~".split('').some(x => x === str)
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 write currently a simple formatting function to replace some placeholders in a string.
var format = function (a, c) {
return a.replace(/{ *([^} ]+) *}/g, function (b, a) {
b = c;
a.replace(/[^.|\[\]]+/g, function (a) {
b = b[a];
});
return b;
});
};
The syntax uses currently curly-bracket notation {key}, I try now to modify the RegExp-pattern to work with one percent instead %key.
var pattern = /{ *([^} ]+) *}/g;
I tried to just replace the parentheses {} with a percent %, but this still doesn't work properly.
var pattern = /% *([^% ]+) */g;
The original pattern works with the following conditions as expected:
var data = {
obj: {
foo: 'Foo',
bar: 'Bar'
},
arr: ['Foo', 'Bar']
};
var objTest = '{obj.foo}, is not equal to {obj.bar}.'
format(objTest, data) // => 'Foo, is not equal to Bar.'
var arrTest = '{arr[0]}, is not equal to {arr[1]}.'
format(arrTest, data) // => 'Foo, is not equal to Bar.'
If we use my modified pattern it seems that the last character after each placeholder-replacement will be removed:
'%obj.foo, is not equal to %obj.bar.' // => 'undefined is not equal to Bar'
'%arr[0], is not equal to %arr[1]' // => 'undefined is not equal to Bar'
Any ideas how to modify the pattern to make it possible to use it with percentage % instead of curly-brackets {}?
You can use this pattern:
var regex = /%([^\b]+)/g;
which means a % sign followed by a complete word. This excludes whitespace characters, underscores, etc.
If you instead want to be able to use those characters as well, you can write:
var regex = /%(\S+)/g;
which is the equivalent of:
var regex = /%([^\s]+)/g;
The reason for this is that your modified regex pattern does not know when to stop matching. In the previous one it terminated at the following } symbol.
This is not an easy thing to fix as there is a myriad of possibilities that could be seen to end your format, here you have a piece of punctuation at the end of each replacement string, i.e. a full stop %arr[1]. or comma %obj.foo,.
So to make this work in your case toy could replace } in the original pattern with [\.,] i.e.
/% *([^% ]+) *[\.,]/g
This will work, but now your replacement pattern needs to always be terminated with either a full stop or comma which i suspect is not exactly what you want. Better to terminate with a know character such as % which would make your matching pattern /% *([^% ]+) *%/g and your format %obj.foo% and you can output a % by doubling up i.e. %obj.bar%%%