I need to capture a number passed as appended integers to a CSS class. My regex is pretty weak, what I'm looking to do is pretty simple. I thought that "negative word boundary" \B was the flag I wanted but I guess I was wrong
string = "foo bar-15";
var theInteger = string.replace('/bar\-\B', ''); // expected result = 15
Use a capture group as outlined here:
var str= "foo bar-15";
var regex = /bar-(\d+)/;
var theInteger = str.match(regex) ? str.match(regex)[1] : null;
Then you can just do an if (theInteger) wherever you need to use it
Try this:
var theInteger = string.match(/\d+/g).join('')
string = "foo bar-15";
var theInteger = /bar-(\d+)/.exec(string)[1]
theInteger // = 15
If you just want the digits at the end (a kind of reverse parseInt), why not:
var num = 'foo bar-15'.replace(/.*\D+(\d+)$/,'$1');
or
var m = 'foo bar-15'.match(/\d+$/);
var num = m? m[0] : '';
Related
I want to do this in node.js
example.js
var str = "a#universe.dev";
var n = str.includes("b#universe.dev");
console.log(n);
but with restriction, so it can search for that string only after the character in this example # so if the new search string would be c#universe.dev it would still find it as the same string and outputs true because it's same "domain" and what's before the character in this example everything before # would be ignored.
Hope someone can help, please
Look into String.prototype.endsWith: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
First, you need to get the end of the first string.
var ending = "#" + str.split("#").reverse()[0];
I split your string by the # character, so that something like "abc#def#ghi" becomes the array ["abc", "def", "ghi"]. I get the last match by reversing the array and grabbing the first element, but there are multiple ways of doing this. I add the separator character back to the beginning.
Then, check whether your new string ends the same:
var n = str.endsWith(ending);
console.log(n);
var str = "a#universe.dev";
var str2 = 'c#universe.dev';
str = str.split('#');
str2 = str2.split('#');
console.log(str[1] ===str2[1]);
With split you can split string based on the # character. and then check for the element on position 1, which will always be the string after #.
Declare the function
function stringIncludeAfterCharacter(s1, s2, c) {
return s1.substr(s1.indexOf(c)) === s2.substr(s2.indexOf(c));
}
then use it
console.log(stringIncludeAfterCharacter('a#universe.dev', 'b#universe.dev', '#' ));
var str = "a#universe.dev";
var n = str.includes(str.split('#')[1]);
console.log(n);
Another way !
var str = "a#universe.dev";
var n = str.indexOf(("b#universe.dev").split('#')[1]) > -1;
console.log(n);
I'm trying to write a Regex that will ignore the first character of a string and start with the second character.
e.g.
str = "14";
test = "4";
This will match ONLY if 4 is is position 2 (end of the string) and NOT at the start, the following will fail
str = "21";
test = "4";
I'm rubbish at Regex and all the options I've tried so far haven't worked.
My current code is like so
filters = filters.replace(/,\s*$/, '');
objRegex = new RegExp('\\/^.{1}(.*)/' + filters, 'gi');
Where filters is a random string consisting of two characters. The current Regex was copied from another SO post but it doesn't work and given my limited knowledge I'm not sure how to make it work, anyone able to help?
Thanks!
I think a Regex is a bit overkill, how about something like this:
var stringToSearch = '14';
var stringToFind = '4';
if (stringToSearch && stringToSearch.length === 2 &&
stringToSearch[1] === stringToFind) {
// do something
}
Just use substring method ?
str = "14";
test = "4";
var str = str.substring(0, 2);
Use following pattern:
"^[\w]{1}4$"
I have string in this format:
var a="input_[2][invoiceNO]";
I want to extract "invoiceNo" string. I've tried:
var a="input_[2][invoiceNO]";
var patt = new RegExp('\[(.*?)\]');
var res = patt.exec(a);
However, I get the following output:
Array [ "[2]", "2" ]
I want to extract only invoiceNo from the string.
Note: Input start can be any string and in place of number 2 it can be any number.
I would check if the [...] before the necessary [InvoiceNo] contains digits and is preceded with _ with this regex:
/_\[\d+\]\s*\[([^\]]+)\]/g
Explanation:
_ - Match underscore
\[\d+\] - Match [1234]-like substring
\s* - Optional spaces
\[([^\]]+)\] - The [some_invoice_123]-like substring
You can even use this regex to find invoice numbers inside larger texts.
The value is in capture group 1 (see m[1] below).
Sample code:
var re = /_\[\d+\]\s*\[([^\]]+)\]/g;
var str = 'input_[2][invoiceNO]';
while ((m = re.exec(str)) !== null) {
alert(m[1]);
}
You can use this regex:
/\[(\w{2,})\]/
and grab captured group #1 from resulting array of String.match function.
var str = 'input_[2][invoiceNO]'
var m = str.match(/\[(\w{2,})\]/);
//=> ["[invoiceNO]", "invoiceNO"]
PS: You can also use negative lookahead to grab same string:
var m = str.match(/\[(\w+)\](?!\[)/);
var a="input_[2][invoiceNO]";
var patt = new RegExp('\[(.*?)\]$');
var res = patt.exec(a);
Try this:
var a="input_[2][invoiceNO]";
var patt = new RegExp(/\]\[(.*)\]/);
var res = patt.exec(a)[1];
console.log(res);
Output:
invoiceNO
You could use something like so: \[([^[]+)\]$. This will extract the content within the last set of brackets. Example available here.
Use the greediness of .*
var a="input_[2][invoiceNO]";
var patt = new RegExp('.*\[(.*?)\]');
var res = patt.exec(a);
This is my code :
var myStr = "/private_images/last-edit/image-work-med.png";
and I'd like to replace the last 7 chars (med.png) with big.png. Or, as you can see, the last occurence after a - split.
How can I do it? I think about regex, but I'm not a champion with them. Tried :
myStr = myStr .replace(/-([^-]*)$/, "big" + '$1');
but it replace the last -, not the last occurence. So the result is /private_images/last-edit/image-workbigmed.png
I'll make a confession: I'm not so great with regexes either.
How about splitting up using split? Less concise, but easier to understand.
var myStr = "/private_images/last-edit/image-work-med.png";
var strs = myStr.split('-');
// Change the last element.
strs[strs.length - 1] = "big.png";
// And put back the right string.
myStr = strs.join('-');
You could use a regex, or you could use a few string methods and make your intentions clear.
var idx = myStr.lastIndexOf("-");
var newStr = myStr.substring(0, idx) + "big.png";
Without using RegExp you could use:
var str = "/private_images/last-edit/image-work-med.png"
,replace = 'big.png'
,nwstr = str.slice(0,str.lastIndexOf('-')+1)+replace;
//=> nwstr now "/private_images/last-edit/image-work-big.png"
More 'functional':
var nwstr = function(s){
return s.replace(s.substr(-7),'');}(
'/private_images/last-edit/image-work-med.png'
)+'big.png'
var url = "/private_images/last-edit/image-work-med.png";
var index = url.lastIndexOf('-');
url = url.substring(0, index+1);
var url2 = "big.png";
var output = url.concat(url2); alert(output);
Check this
Just add '-' to your regex and to the replacement string:
myStr = myStr .replace(/-([^-]*)\.png$/, "-big.png");
Or if you want the file extension to be variable:
myStr = myStr .replace(/-([^-]*)\.([a-z]+)$/, "-big.$2");
Why not just use replace:
var myStr = "/private_images/last-edit/image-work-med.png";
var newStr = myStr.replace("med.png", "big.png");
According to the requirements specified in your question this would suffice.
If you know it will be a .png file:
var ex = new Regex(#"-\w*.png$");
var myStr = "/private_images/last-edit/image-work-med.png";
myStr = ex.Replace(myStr, "-big.png");
It works but if its a jpg it wont...
If you want to use string functions -
var myStr = "/private_images/last-edit/image-work-med.png";
var cleanedupStr = myStr.slice(0, myStr.lastIndexOf("-"));
String.slice
i have a string like this .
var url="http://localhost/elephanti2/chaink/stores/stores_ajax_page/5/b.BusinessName/asc/1/11"
i want to get substrings
http://localhost/elephanti2/chaink/stores/stores_ajax_page
and
5/b.BusinessName/asc/1/11
i want to split string from the 7 th slash and make the two sub-strings
how to do this ??,
i looked for split()
but in this case if i use it i have to con-cat the sub-strings and make what i want . is there a easy way ??
try this one:
var url="http://localhost/elephanti2/chaink/stores/stores_ajax_page/5/b.BusinessName/asc/1/11";
var parts = url.split('/');
var p1 = parts.slice(0,6).join('/');
var p2 = parts.slice(7).join('/');
alert(p1);
alert(p2);
p1 should get the first part and p2 is the second part
You can try this regex. Generally if your url pattern always follow this structure, it will work.
var pattern = /(\w+:\/\/(\w+\/){5})/i;
var url = "http://localhost/elephanti2/chaink/stores/stores_ajax_page/5/b.BusinessName/asc/1/11";
var result = url.split(pattern);
alert(result[1]);
alert(result[3]);
Try this :
var str = 'http://localhost/elephanti2/chaink/stores/stores_ajax_page/5/b.BusinessName/asc/1/11',
delimiter = '/',
start = 7,
tokens = str.split(delimiter).slice(start),
result = tokens.join(delimiter);
var match = str.match(/([^\/]*\/){5}/)[0];
Find this fiddle