js Regex not working as expected. Newline not getting detected [duplicate] - javascript

This question already has answers here:
Why it's not possible to use regex to parse HTML/XML: a formal explanation in layman's terms
(10 answers)
XML parsing of a variable string in JavaScript
(10 answers)
The best node module for XML parsing [closed]
(2 answers)
Closed 4 years ago.
I have a string as follows:
<abc name = "foo">
<child>bar</child>
</abc>
<xyz>1</xyz>
<abc name = "foo2">
<child>bar2</child>
</abc>
<xyz>5</xyz>
I have created a regex as follows:
var regexapi = /<abc\s*name\s*=\s*"(.*?)"[\s\S]*?<\/abc>\n*<xyz>/gim;
while ( (resApi = regexapi.exec(data))) {
array1.push(resApi[0]);
}
console.log(array1[0]);
Now if I don't have the tag <xyz>1</xyz> printing array1[0] should show undefined but it is printing as follows:
<abc name = "foo">
<child>bar</child>
</abc>
<abc name = "foo2">
<child>bar2</child>
</abc>
<xyz>
I think there is some problem in \n* since I'm giving multiline flag. Not sure aout this though.
Note that this is without <xyz>1</xyz> tag. I want it to print undefined.
Thanks.

Regex:
<\/abc>\n(?:<xyz>(.*)(?=<\/xyz))*
Regex Demo
js Demo
Matches a </abc> followed by <xyz> and value. if <xyz> tag is missing array[0] will return an empty string (not undefined)

You would be better off using an XML parser here. If you insist on using regex, here is one option:
var input = "<abc name = \"foo\">\n\t<child>bar</child>\n</abc>\n<xyz>\n\n<abc name = \"foo2\">\t\n<child>bar2</child>\n</abc>\n<xyz>35</xyz>";
var regex = /<abc[^>]*>(?:(?!<\/abc>)[\s\S]*)<\/abc>\s*<xyz>((?!<xyz>)[\s\S]*)<\/xyz>/g;
var match = regex.exec(input);
console.log(match[1]); // 35
This matches an <abc> tag followed by optional whitespace, then followed immediately by an <xyz> tag. Should that tag be empty, then nothing would be capture in the first capture group match[1].

Related

JavaScript replace regex with array element [duplicate]

This question already has an answer here:
Why this javascript regex doesn't work?
(1 answer)
Closed 3 years ago.
Trying to replace everything inside brackets [ ] with an element of an array. Example:
function replacingText(){
var names = ["Cole", "Kyle", "Chase"];
var sentance = 'This is [Cole].'
var regex = "\[(.*?)\]/gm";
console.log(sentance.replace(regex, names[1]));
}
So the output should be 'This is Kyle.' instead of 'This is [Cole].'
The only thing that needs fixed is the regex string needs to be
var regex = /\[(.*?)\]/gm;
The /gm on the end just means it wont stop at the first one it finds and the "m" stands for multi-line matching.
The javascript string replace can accept both strings and regular expressions as the first argument. See the examples presented here.
In your case you are passing the first as a string of a regular expression: "\[(.*?)\]"
Instead you should either match the exact string sentence.replace("[Cole]", names[1]) or, what you probably want, is to use the regular expression to match any name sentence.replace(/\[.+\]/g, names[1]) (note that the first argument does not contain any quotes)
The /g (global) is used to match all occurrences in the sentence. Otherwise only the first occurrence would be replaced.
Could you try this :
function replacingText() {
var names = ["Cole", "Kyle", "Chase"];
var sentance = "This is [Cole] [ahmed]";
var regex = /\[([0-9]|[aA-zZ])*\]/g;
console.log(sentance.replace(regex, names[1]));
}
I just tried it and it works as expected

Regex replace all occurrences of text WITH brackets [duplicate]

This question already has answers here:
Javascript/regex: Remove text between square brackets
(4 answers)
Closed 5 months ago.
In short i need to replace every occurrence of text betweeen brackets including the brackets in a string, and the text to be replaced will be in a variable in Javascript.
A simple regex in a replace method wont work because of the brackets.
Example, replace "[test] [teste] test [hello]" with a variable with the value of "hi".
Output: "hi hi test [hello]"
"[test] [teste] test".replace(/\[.*?\]/g, 'hi')
escape the brackets with "\" and use g flag
edit: removed the i flag and chnaged w to . to handle anything inside brackets
I'm not quite sure what you're looking for but .match will store off the matches in an array and .replace will perform the replace for you.
const regex = /\[.*?\]/g;
var mutable = "[test] [teste] test";
const matches = mutable.match(regex); // Save all matches to an array
mutable = mutable.replace(regex, 'dude'); // Replace matches
console.log(mutable);
console.log(matches);
So, the way i found to do it was to get my variable to be replaced, example:
var test= "[test]",
Then i replaced the brackets in it so it would become "\[test\]", then i used:
var regex = new RegExp(test+"+","gm")
then i used this regex in JS replace method.

How to Replace Colon and Star Special Characters in JavaScript Regex [duplicate]

This question already has answers here:
Replace multiple characters in one replace call
(21 answers)
Closed 4 years ago.
I am trying to replace star (*) and colon (:) with an empty string ("") and the string can be as follows:
Either: Registration No: already exists*
OR: *Registration No: already exists
So, I don't want (*) as well as (:) and output should be Registration No already exists how can I solve it.
Trying as follows:
var txt = str.replace(/:\*/ig,"");
Please help me and thanks in advance
You regex matches :*. You could match either of them using a character class:
var txt = str.replace(/[:*]/g,"");
const strings = [
"Registration No: already exists*",
"*Registration No: already exists"
];
strings.forEach((s) => {
console.log(s.replace(/[:*]/g, ""));
});
Another way without using a character class is to use a pipe or alteration to separate each group. This however, requires that you escape special characters and this does allow for group matches instead of single character matches:
var txt = str.replace(/:|\*/ig, "");

Replace '-' with '--' in a JavaScript string [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I am trying to replace a single dash '-' character in a string with double dashes.
2015–09–01T16:00:00.000Z
to be
2015-–09-–01T16:00:00.000Z
This is the code I am using but it doesn't seem to be working:
var temp = '2015–09–01T16:00:00.000Z'
temp.replace(/-/g,'--')
In JavaScript Strings are immutable. So, when you modify a string, a new string object will be created with the modification.
In your case, the replace has replaced the characters but returns a new string. You need to store that in a variable to use it.
For example,
var temp = '2015–09–01T16:00:00.000Z';
temp = temp.replace(/–/g,'--');
Note The string which you have shown in the question, when copied, I realised that it is a different character but looks similar to – and it is not the same as hyphen (-). The character codes for those characters are as follows
console.log('–'.charCodeAt(0));
// 8211: en dash
console.log('-'.charCodeAt(0));
// 45: hyphen
The hyphen character – you have in the string is different from the one you have in the RegExp -. Even though they look alike, they are different characters.
The correct RegExp in this case is temp.replace(/–/g,'--')
Probably the easiest thing would be to just use split and join.
var temp = '2015–09–01T16:00:00.000Z'.split("-").join("--");

Removing any character besides 0-9 + - / * and ^ [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I'm trying to further my understanding of regular expressions in JavaScript.
So I have a form that allows a user to provide any string of characters. I'd like to take that string and remove any character that isn't a number, parenthesis, +, -, *, /, or ^. I'm trying to write a negating regex to grab anything that isn't valid and remove it. So far the code concerning this issue looks like this:
var pattern = /[^-\+\(\)\*\/\^0-9]*/g;
function validate (form) {
var string = form.input.value;
string.replace(pattern, '');
alert(string);
};
This regex works as intended on http://www.infobyip.com/regularexpressioncalculator.php regex tester, but always alerts with the exact string I supply without making any changes in the calculator. Any advice or pointers would be greatly appreciated.
The replace method doesn't modify the string. It creates a new string with the result of the replacement and returns it. You need to assign the result of the replacement back to the variable:
string = string.replace(pattern, '');

Categories