How to detect a series of characters in a string? - javascript

For example, I have a string:
"This is the ### example"
I would like to substring the ### out of the above string?
The number of Hash keys may vary, so I would like to find out and replace the ### pattern with, say, 001 for example.
Can anybody help?

You can also do a replace. I am familiar with the C# version of this,
string stringValue = "Thia is the ### example";
stringValue.Replace("###", "");
This would remove ### completely from the above string. Again you would have to know the exact string.
In JavaScript, it's similar - .replace (with a lowercase r) is used. So:
var stringValue = "This is the ### example";
var replacedValue = stringValue.replace('###', '');

You'll want to investigate either "Regular Expressions" for this, or, if you know the precise position and length of the characters you are interested in, you can simply use String's .substring method.

If you want to capture multiple # characters, then you'll need regular expressions:
var myString = "This is #### the example";
var result = myString.replace(/#+/g, '');
If you want to remove the space too, you can use the regex /#+\s|\s#+|#+/.

If the rest of the string is known, just get the part that you need:
var example = str.substr(12, str.length - 20);

The javascript match method will return an array of substrings matching a regular expression. You can use this to determine the number of matching characters to be replaced. Assuming you want to replace each octothorpe with a random digit, you could use code like this:
var exampleStr = "This is the ### example";
var swapThese = exampleStr.match(/#/g);
if (swapThese) {
for (var i=0;i<swapThese.length;i++) {
var swapThis = new RegExp(swapThese[i]);
exampleStr = exampleStr.replace(swapThis,Math.floor(Math.random()*9));
}
}
alert(exampleStr); // or whatever you want to do with it
Note that the code only loops the length of the array if it's present: if (swapThese) {
This check is necessary because if the match method finds no matches, it returns null rather than an empty array. Trying to iterate through null value will break.

Related

JavaScript escape stars on regular expression

I am trying to get a serial number from a zigbee packet (i.e get from 702442500 *13*32*702442500#9).
So far, I've tried this:
test = "*#*0##*13*32*702442500#9##";
test.match("\*#\*0##\*13\*32\*(.*)#9##");
And this:
test.match("*#*0##*13*32*(.*)#9##");
With no luck. How do I get a valid regular expression that does what I want?
The below regex matches the number which has atleast three digits,
/([0-9][0-9][0-9]+)/
DEMO
If you want to extract the big number, you can use:
/\*#\*0##\*13\*32\*([^#]+)#9##/
Note that I use delimiters / that are needed to write a pattern in Javascript (without the regexp object syntax). When you use this syntax, (double)? quotes are not needed. I use [^#]+ instead of .* because it is more clear and more efficent for the regex engine.
The easiest way to grab that portion of the string would be to use
var regex = /(\*\d{3,}#)/g,
test = "*13*32*702442500#9";
var match = test.match(regex).slice(1,-1);
This captures a * followed by 3 or more \d (numbers) until it reaches an octothorpe. Using the global (/g) modifier will cause it to return an array of matches.
For example, if
var test = "*13*32*702442500#9
*#*0##*13*32*702442500#9##";
then, test.match(regex) will return ["*702442500#", "*702442500#"]. You can then slice the elements of this array:
var results = [],
test = "... above ... ",
regex = /(\*\d{3,}#)/g,
matches = test.match(regex);
matches.forEach(function (d) {
results.push(d.slice(1,-1));
})
// results : `["702442500", "702442500"]`

Match a string if it comes after certain string

I need a regular expression for JavaScript to match John (case insensitive) after Name:
I know how to do it, but I don't know how to get string from a different line like so (from a textarea):
Name
John
This is what I tried to do :: var str = /\s[a-zA-Z0-9](?= Name)/;
The logic: get a string with letter/numbers on a linespace followed by Name.
Then, I would use the .test(); method.
EDIT:
I tried to make the question more simple than it should have been. The thing I don't quite understand is how do I isolate "John" (really anything) on a new line followed by a specific string (in this case Name).
E.g., IF John comes after Name {dosomething} else{dosomethingelse}
Unfortunately, JavaScript doesn't support look-behinds. For something this simple, you can just match both parts of the string like this:
var str = /Name\s+([a-zA-Z0-9]+)/;
You then just have to extract the first capture group if you want to get John. For example:
"Name\n John".match(/Name\s+([a-zA-Z0-9]+)/)[1]; // John
However if you're just using .test, the capture group isn't necessary. For example:
var input = "Name\n John";
if (/Name\s+[a-zA-Z0-9]+/.test(input)) {
// dosomething
} else{
// dosomethingelse
}
Also, if you need to ensure that Name and John appear on separate lines with nothing but whitespace in between, you can use this pattern with the multi-line (m) flag.
var str = /Name\s*^\s*([a-zA-Z0-9]+)/m;
You do not need a lookahead here, simply place Name before the characters you want to match. And to enable case-insensitive matching, place the i modifier on the end of your regular expression.
var str = 'Name\n John'
var re = /Name\s+[a-z0-9]+/i
if (re.test(str)) {
// do something
} else {
// do something else
}
Use the String.match method if you want to extract the name from the string.
'Name\n John'.match(/Name\s+([a-z0-9]+)/i)[1];
The [1] here refers back to what was matched/captured in capturing group #1

Need a regex that finds "string" but not "[string]"

I'm trying to build a regular expression that parses a string and skips things in brackets.
Something like
string = "A bc defg hi [hi] jkl mnop.";
The .match() should return "hi" but not [hi]. I've spent 5 hours running through RE's but I'm throwing in the towel.
Also this is for javascript or jquery if that matters.
Any help is appreciated. Also I'm working on getting my questions formatted correctly : )
EDIT:
Ok I just had a eureka moment and figured out that the original RegExp I was using actually did work. But when I was replaces the matches with the [matches] it simply replaced the first match in the string... over and over. I thought this was my regex refusing to skip the brackets but after much time of trying almost all of the solutions below, I realized that I was derping Hardcore.
When .replace was working its magic it was on the first match, so I quite simply added a space to the end of the result word as follows:
var result = string.match(regex);
var modifiedResult = '[' + result[0].toString() + ']';
string.replace(result[0].toString() + ' ', modifiedResult + ' ');
This got it to stop targeting the original word in the string and stop adding a new set of brackets to it with every match. Thank you all for your help. I am going to give answer credit to the post that prodded me in the right direction.
preprocess the target string by removing everything between brackets before trying to match your RE
string = "A bc defg hi [hi] jkl mnop."
tmpstring = string.replace(/\[.*\]/, "")
then apply your RE to tmpstring
correction: made the match for brackets eager per nhahtd comment below, and also, made the RE global
string = "A bc defg hi [hi] jkl mnop."
tmpstring = string.replace(/\[.*?\]/g, "")
You don't necessarily need regex for this. Simply use string manipulation:
var arr = string.split("[");
var final = arr[0] + arr[1].split("]")[1];
If there are multiple bracketed expressions, use a loop:
while (string.indexOf("[") != -1){
var arr = string.split("[");
string = arr[0] + arr.slice(1).join("[").split("]").slice(1).join("]");
}
Using only Regular Expressions, you can use:
hi(?!])
as an example.
Look here about negative lookahead: http://www.regular-expressions.info/lookaround.html
Unfortunately, javascript does not support negative lookbehind.
I used http://regexpal.com/ to test, abcd[hi]jkhilmnop as test data, hi(?!]) as the regex to find. It matched 'hi' without matching '[hi]'. Basically it matched the 'hi' so long as there was not a following ']' character.
This of course, can be expanded if needed. This has a benefit of not requiring any pre-processing for the string.
r"\[(.*)\]"
Just play arounds with this if you wanto to use regular expressions.
What do yo uwant to do with it? If you want to selectively replace parts like "hi" except when it's "[hi]", then I often use a system where I match what I want to avoid first and then what I want to watch; if it matches what I want to avoid then I return the match, otherwise I return the processed match.
Like this:
return string.replace(/(\[\w+\])|(\w+)/g, function(all, m1, m2) {return m1 || m2.toUpperCase()});
which, with the given string, returns:
"A BC DEFG HI [hi] JKL MNOP."
Thus: it replaces every word with uppercase (m1 is empty), except if the word is between square brackets (m1 is not empty).
This builds an array of all the strings contained in [ ]:
var regex = /\[([^\]]*)\]/;
var string = "A bc defg hi [hi] [jkl] mnop.";
var results=[], result;
while(result = regex.exec(string))
results.push(result[1]);
edit
To answer to the question, this regex returns the string less all is in [ ], and trim whitespaces:
"A bc defg [hi] mnop [jkl].".replace(/(\s{0,1})\[[^\]]*\](\s{0,1})/g,'$1')
Instead of skipping the match you can probably try something different - match everything but do not capture the string within square brackets (inclusive) with something like this:
var r = /(?:\[.*?[^\[\]]\])|(.)/g;
var result;
var str = [];
while((result = r.exec(s)) !== null){
if(result[1] !== undefined){ //true if [string] matched but not captured
str.push(result[1]);
}
}
console.log(str.join(''));
The last line will print parts of the string which do not match the [string] pattern. For example, when called with the input "A [bc] [defg] hi [hi] j[kl]u m[no]p." the code prints "A hi ju mp." with whitespaces intact.
You can try different things with this code e.g. replacing etc.

RegExp match a single quoted text without quotes - JavaScript

I'm sorry if it is a confusing question. I was trying to find a way to do this but couldn't find it so, if it is a repeated question, my apologies!
I have a text something like this: something:"askjnqwe234"
I want to be able to get askjnqwe234 using a RegExp. You can notice I want to omit the quotes. I was trying this using /[^"]+(?=(" ")|"$)/g but it returns an array. I want a RegExt to return a single string, not an array.
I don't know if it's possible but I do not want to specify the position of the array; something like this:
var x = string.match(/[^"]+(?=(" ")|"$)/g)[0];
Thanks!
Try:
/"([^"]*)"/g
in English: look for " the match and record anything that isn't " till you see another "".
match and exec always return an array or null, so, assuming you have a single double-quoted value and no newlines in the string, you could use
var x;
var str = 'something:"askjnqwe234"';
x = str.replace( /^[^"]*"|".*/g, '' );
// "askjnqwe234"
Or, if you may have other quoted values in the string
x = str.replace( /.*?something:"([^"]*)".*/, '$1' );
where $1 refers to the substring captured by the sub-pattern [^"]* between the ().
Further explanation on request.
Notwithstanding the above, I recommend that you tolerate the array indexing and just use match.
You can capture the information inside quotes like this, assuming it matches:
var x = string.match(/something:"([^"]*)"/)[1];
The memory capture at index 1 is the part inside the double quotes.
If you're not sure it will match:
var match = string.match(/something:"([^"]*)"/);
if (match) {
// use match[1] here
}

assign matched values from jquery regex match to string variable

I am doing it wrong. I know.
I want to assign the matched text that is the result of a regex to a string var.
basically the regex is supposed to pull out anything in between two colons
so blah:xx:blahdeeblah
would result in xx
var matchedString= $(current).match('[^.:]+):(.*?):([^.:]+');
alert(matchedString);
I am looking to get this to put the xx in my matchedString variable.
I checked the jquery docs and they say that match should return an array. (string char array?)
When I run this nothing happens, No errors in the console but I tested the regex and it works outside of js. I am starting to think I am just doing the regex wrong or I am completely not getting how the match function works altogether
I checked the jquery docs and they say that match should return an array.
No such method exists for jQuery. match is a standard javascript method of a string. So using your example, this might be
var str = "blah:xx:blahdeeblah";
var matchedString = str.match(/([^.:]+):(.*?):([^.:]+)/);
alert(matchedString[2]);
// -> "xx"
However, you really don't need a regular expression for this. You can use another string method, split() to divide the string into an array of strings using a separator:
var str = "blah:xx:blahdeeblah";
var matchedString = str.split(":"); // split on the : character
alert(matchedString[1]);
// -> "xx"
String.match
String.split

Categories

Resources