Regex doesn't seem to work properly in my code - javascript

What I am trying to do is turn, for example "{{John}}" into "John".
First I am parsing from a string:
var parametrar = content.match(/[{{]+[Aa-Åå]+[}}]/g);
Here regex works fine and it parses as it should. I need to parse the "{}" to find stuff in the string.
But then I'm trying to parse out the "{}" from each "parametrar":
for (var i = 0; i < parametrar.length; i++) {
parametrar = parametrar[i].replace(/[{}]/g, "");
}
When I alert "parametrar" all I get is one "a". I have no idea what I'm doing wrong here, seems it should work.

Try to add greedy matching to maque's answer with using question mark(?).
"{{John}}".replace(/\{\{(.*?)\}\}/g,"$1");
It extracts "John" properly from "{{John}} and Martin}}" input. Otherwise it matches to "John}} and Martin".

You can match the name with braces around and then just use the first capturing group (m[1]):
var re = /\{{2}([a-zA-ZÅå]+)\}{2}/g;
var str = '{{John}}';
if ((m = re.exec(str)) !== null) {
paramterar = m[1];
alert(paramterar);
}
If you have a larger string that contains multiple {{NAME}}s, you can use the code I suggested in my comment:
var re = /\{{2}([a-zA-ZÅå]+)\}{2}/g;
var str = 'My name is {{John}} and {{Vasya}}.';
var arr = [];
while ((m = re.exec(str)) !== null) {
paramterar = m[1];
arr.push(m[1]);
}
alert(arr);
alert(str.replace(/([a-zA-ZÅå])\}{2}/g,"$1").replace(/\{{2}(?=[a-zA-ZÅå])/g, ""))
I have also fixed the character class to only accept English letters + Å and å (revert if it is not the case, but note that [Aa-Åå] is not matching any upper case Englihs letters from B to Z, and matches characters like §.) Please check the ANSI table to see what range you need.

Just do it like that:
"{{John}}".replace(/\{\{(.*)\}\}/g,"$1");
So you are searching for string that have double '{' (these needs to be escaped), then there is something (.*) then again '}' and your output is first match of the block.

Try this:
var parametrar = content.replace(/\{\{([a-åA-Å]+)\}\}/g, "$1");
This gives you a "purified" string. If you want an array, than you can do this:
var parametrar = content.match(/\{\{[a-åA-Å]+\}\}/g);
for (var i = 0, len = parametrar.length; i < len; i++) {
parametrar = parametrar[i].replace(/\{\{([a-åA-Å]+)\}\}/g, "$1");
}

Related

How to String include after character in nodejs, JavaScript

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

Removing commas unless inside quotes, not using regexp

I am trying to remove commas in a string unless they appear inside quotes.
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '';
mystring = mystring.split(',').join(newchar);// working correctly
document.write(mystring);
Output I have is
this is a test example "i dont know" jumps
Expected output
this is a test example "i, dont know" jumps
A couple of questions. How can I find the index of string so that inside the quotation it will include comma but outside of quotation " it will not include comma ,. I know I have to use indexOf and substring but I don't know how to format it? (No regex please as I'm new to JavaScript and I'm just focusing on the basics.)
Loop through the string, remembering whether or not you are inside a set of quotation marks, and building a new string to which the commas inside quotes are not added:
var inQuotes = false; // Are we inside quotes?
var result = ''; // New string we will build.
for (var i = 0; i < str.length; i++) { // Loop through string.
var chr = str[i]; // Extract character.
var isComma = chr === ','; // Is this a comma?
var isQuote = chr === '"'; // Is this a quote?
if (inQuotes || !isComma) { // Include this character?
if (isQuote) inQuotes = !inQuotes; // If quote, reverse quote status.
result += chr; // Add character to result.
}
}
This solution has the advantage compared to the accepted one that it will work properly even if the input has multiple quotes strings inside it.
This will work, but it's not ideal for all cases. Example: It will not work for a string with more than 2 quotation marks.
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '';
var firstIndex = mystring.indexOf("\"");
var lastIndex = mystring.lastIndexOf("\"");
var substring1 = mystring.substring(0,firstIndex).split(',').join(newchar);
var substring2 = mystring.substring(lastIndex).split(',').join(newchar);
mystring = substring1 + mystring.substring(firstIndex, lastIndex) + substring2;
document.write(mystring);
Some day you need to start using regexp, than regexr.com is your friend. The regexp solution is simple:
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '_';
mystring = mystring.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g).join(newchar);// working correctly
document.write(mystring);

Remove part of string that contains a tag

I have a variable in JavaScript that holds the below value:
<label>AAA</label>
I need just the AAA. I try to replace the characters but it is failing. Would someone please suggest the best approach?
var company="<label>AAA</label>";// I am getting this value from element
var rx = new RegExp("((\\$|)(([1-9]\\d{0,2}(\\,\\d{3})*|([1-9]\\d*))(\\.\\d{2})))|(\\<)*(\\>)");
var arr = rx.exec(company);
var arr1 = company.match(rx);
if (arr[1] != null) {
var co = arr[1].replace(",", "");
}
}
As you say you need only AAA, consider the below code.
I have taken a substring between the first '>' character in the string company, added 1 to that and the last < character. However, if the company var contains more of such < or >, you could go for a regex approach.
var company="<label>AAA</label>";
alert(company.substring(company.indexOf('>')+1, company.lastIndexOf('<')));

Replace string between second set of [ and ]

I am learning regex, and I got a doubt. Let's consider
var s = "YYYN[1-20]N[]NYY";
Now, I want to replace/insert the '1-8' between [ and ] at its second occurrence.
Then output should be
YYYN[1-20]N[1-8]NYY
For that I had tried using replace and passing a function through it as shown below:
var nth = 0;
s = s.replace(/\[([^)]+)\]/g, function(match, i, original) {
nth++;
return (nth === 1) ? "1-8" : match;
});
alert(s); // But It wont work
I think that regex is not matchIing the string that I am using.
How can I fix it?
You regex \[([^)]+)\] will not match empty square brackets since + requires at least 1 character other than ). I guess you wanted to write \[[^\]]*\].
Here is a fix for your solution:
var s = "YYYN[1-20]N[]NYY";
var nth = 0;
s = s.replace(/\[[^\]]*\]/g, function (match, i, original) {
nth++;
return (nth !== 1) ? "[1-8]" : match;
});
alert(s);
Here is another way of doing it:
var s = "YYYN[1-20]N[]NYY";
var nth = 0;
s = s.replace(/(.*)\[\]/, "$1[1-8]");
alert(s);
The regex (.*)\[\] matches and captures into Group 1 greedily as much text as possible (thus we get the last set of empty []), and then matches empty square brackets. Then we restore the text before [] with $1 backreference and add out string 1-8.
If it’s only two occurences of square brackets, then this will work:
/(.*\[.*?\].*\[).*?(\].*)/
This RegEx has “YYYN[1-20]N[” as the first capturing group and “]NYY” as the second.
I suggest using simple split and join operations:
var s = "YYYN[1-20]N[]NYY";
var arr = s.split(/\[/)
arr[2] = '1-8' + arr[2]
var r = arr.join('[')
//=> YYYN[1-20]N[1-8]NYY
You can use following regex :
var s = "YYYN[1-20]N[]NYY";
var nth = 0;
s = s.replace(/([^[]+\[(?:[^[]+)\][^[]+)\[[^[]+\](.+)/, "$1[1-8]$2");
alert(s);
The first part ([^[]+\[([^[]+)\][^[]+) will match a string contain first sub-string between []. and \[[^[]+\] would be the second one which you want and the last part (.+?) match the rest of your string.

Javascript regex - split string

Struggling with a regex requirement. I need to split a string into an array wherever it finds a forward slash. But not if the forward slash is preceded by an escape.
Eg, if I have this string:
hello/world
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = world
And if I have this string:
hello/wo\/rld
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = wo/rld
Any ideas?
I wouldn't use split() for this job. It's much easier to match the path components themselves, rather than the delimiters. For example:
var subject = 'hello/wo\\/rld';
var regex = /(?:[^\/\\]+|\\.)+/g;
var matched = null;
while (matched = regex.exec(subject)) {
print(matched[0]);
}
output:
hello
wo\/rld
test it at ideone.com
The following is a little long-winded but will work, and avoids the problem with IE's broken split implementation by not using a regular expression.
function splitPath(str) {
var rawParts = str.split("/"), parts = [];
for (var i = 0, len = rawParts.length, part; i < len; ++i) {
part = "";
while (rawParts[i].slice(-1) == "\\") {
part += rawParts[i++].slice(0, -1) + "/";
}
parts.push(part + rawParts[i]);
}
return parts;
}
var str = "hello/world\\/foo/bar";
alert( splitPath(str).join(",") );
Here's a way adapted from the techniques in this blog post:
var str = "Testing/one\\/two\\/three";
var result = str.replace(/(\\)?\//g, function($0, $1){
return $1 ? '/' : '[****]';
}).split('[****]');
Live example
Given:
Testing/one\/two\/three
The result is:
[0]: Testing
[1]: one/two/three
That first uses the simple "fake" lookbehind to replace / with [****] and to replace \/ with /, then splits on the [****] value. (Obviously, replace [****] with anything that won't be in the string.)
/*
If you are getting your string from an ajax response or a data base query,
that is, the string has not been interpreted by javascript,
you can match character sequences that either have no slash or have escaped slashes.
If you are defining the string in a script, escape the escapes and strip them after the match.
*/
var s='hello/wor\\/ld';
s=s.match(/(([^\/]*(\\\/)+)([^\/]*)+|([^\/]+))/g) || [s];
alert(s.join('\n'))
s.join('\n').replace(/\\/g,'')
/* returned value: (String)
hello
wor/ld
*/
Here's an example at rubular.com
For short code, you can use reverse to simulate negative lookbehind
function reverse(s){
return s.split('').reverse().join('');
}
var parts = reverse(myString).split(/[/](?!\\(?:\\\\)*(?:[^\\]|$))/g).reverse();
for (var i = parts.length; --i >= 0;) { parts[i] = reverse(parts[i]); }
but to be efficient, it's probably better to split on /[/]/ and then walk the array and rejoin elements that have an escape at the end.
Something like this may take care of it for you.
var str = "/hello/wo\\/rld/";
var split = str.replace(/^\/|\\?\/|\/$/g, function(match) {
if (match.indexOf('\\') == -1) {
return '\x00';
}
return match;
}).split('\x00');
alert(split);

Categories