How to ignore newline in regexp? - javascript

How to ignore newline in regexp in Javascript ?
for example:
data = "\
<test>11\n
1</test>\n\
#EXTM3U\n\
"
var reg = new RegExp( "\<" + "test" + "\>(.*?)\<\/" + "test" + "\>" )
var match = data.match(reg)
console.log(match[1])
result: undefined

In JavaScript, there is no flag to tell to RegExp() that . should match newlines. So, you need to use a workaround e.g. [\s\S].
Your RegExp would then look like this:
var reg = new RegExp( "\<" + "test" + "\>([\s\S]*?)\<\/" + "test" + "\>" );

You are missing a JS newline character \ at the end of line 2.
Also, change regexp to:
var data = "\
<test>11\n\
1</test>\n\
#EXTM3U\n\
";
var reg = new RegExp(/<test>(.|\s)*<\/test>/);
var match = data.match(reg);
console.log(match[0]);
http://jsfiddle.net/samliew/DPc2E/

By reading this one: How to use JavaScript regex over multiple lines?
I came with that, which works:
var data = "<test>11\n1</test>\n#EXTM3U\n";
reg = /<test>([\s\S]*?)<\/test>/;
var match = data.match(reg);
console.log(match[1]);
Here is a fiddle: http://jsfiddle.net/Rpkj2/

Better you can use [\s\S] instead of . for multiline matching.
It is the most common JavaScript idiom for matching everything including newlines. It's easier on the eyes and much more efficient than an alternation-based approach like (.|\n).

EDIT: Got it:
I tried to use this regex in notepad++ But the problem is that it finds the whole text from beginning to end
MyRegex:
<hostname-validation>(.|\s)*<\/pathname-validation> (finds everything)
/<hostname-validation>(.|\s)*<\/pathname-validation>/ (finds nothing)
/\<hostname-validation\>([\s\S]*?)\<\/pathname-validation\>/ (finds nothing)
**<hostname-validation>([\s\S]*?)<\/pathname-validation> (my desired result)**
The text where I use in:
<hostname-validation>www.your-tag-name.com</hostname-validation>
<pathname-validation>pathname</pathname-validation> <response-validation nil="true"/>
<validate-absence type="boolean">false</validate-absence> (...) <hostname-validation>www.your-tag-name.com</hostname-validation>
<pathname-validation>pathname</pathname-validation> <response-validation nil="false"/>
<validate-absence type="boolean">false</validate-absence> (...) <hostname-validation>www.your-tag-name.com</hostname-validation>
<pathname-validation>pathname</pathname-validation> <response-validation nil="true"/>
<validate-absence type="boolean">false</validate-absence> (...)

Related

How to put a variable in my JS regular expression? [duplicate]

I want to add a (variable) tag to values with regex, the pattern works fine with PHP but I have troubles implementing it into JavaScript.
The pattern is (value is the variable):
/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is
I escaped the backslashes:
var str = $("#div").html();
var regex = "/(?!(?:[^<]+>|[^>]+<\\/a>))\\b(" + value + ")\\b/is";
$("#div").html(str.replace(regex, "" + value + ""));
But this seem not to be right, I logged the pattern and its exactly what it should be.
Any ideas?
To create the regex from a string, you have to use JavaScript's RegExp object.
If you also want to match/replace more than one time, then you must add the g (global match) flag. Here's an example:
var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
In the general case, escape the string before using as regex:
Not every string is a valid regex, though: there are some speciall characters, like ( or [. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:
function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
Note: the regex in the question uses the s modifier, which didn't exist at the time of the question, but does exist -- a s (dotall) flag/modifier in JavaScript -- today.
If you are trying to use a variable value in the expression, you must use the RegExp "constructor".
var regex = "(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b";
new RegExp(regex, "is")
I found I had to double slash the \b to get it working. For example to remove "1x" words from a string using a variable, I needed to use:
str = "1x";
var regex = new RegExp("\\b"+str+"\\b","g"); // same as inv.replace(/\b1x\b/g, "")
inv=inv.replace(regex, "");
You don't need the " to define a regular expression so just:
var regex = /(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is; // this is valid syntax
If value is a variable and you want a dynamic regular expression then you can't use this notation; use the alternative notation.
String.replace also accepts strings as input, so you can do "fox".replace("fox", "bear");
Alternative:
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(.*?)\b/", "is");
Keep in mind that if value contains regular expressions characters like (, [ and ? you will need to escape them.
I found this thread useful - so I thought I would add the answer to my own problem.
I wanted to edit a database configuration file (datastax cassandra) from a node application in javascript and for one of the settings in the file I needed to match on a string and then replace the line following it.
This was my solution.
dse_cassandra_yaml='/etc/dse/cassandra/cassandra.yaml'
// a) find the searchString and grab all text on the following line to it
// b) replace all next line text with a newString supplied to function
// note - leaves searchString text untouched
function replaceStringNextLine(file, searchString, newString) {
fs.readFile(file, 'utf-8', function(err, data){
if (err) throw err;
// need to use double escape '\\' when putting regex in strings !
var re = "\\s+(\\-\\s(.*)?)(?:\\s|$)";
var myRegExp = new RegExp(searchString + re, "g");
var match = myRegExp.exec(data);
var replaceThis = match[1];
var writeString = data.replace(replaceThis, newString);
fs.writeFile(file, writeString, 'utf-8', function (err) {
if (err) throw err;
console.log(file + ' updated');
});
});
}
searchString = "data_file_directories:"
newString = "- /mnt/cassandra/data"
replaceStringNextLine(dse_cassandra_yaml, searchString, newString );
After running, it will change the existing data directory setting to the new one:
config file before:
data_file_directories:
- /var/lib/cassandra/data
config file after:
data_file_directories:
- /mnt/cassandra/data
Much easier way: use template literals.
var variable = 'foo'
var expression = `.*${variable}.*`
var re = new RegExp(expression, 'g')
re.test('fdjklsffoodjkslfd') // true
re.test('fdjklsfdjkslfd') // false
Using string variable(s) content as part of a more complex composed regex expression (es6|ts)
This example will replace all urls using my-domain.com to my-other-domain (both are variables).
You can do dynamic regexs by combining string values and other regex expressions within a raw string template. Using String.raw will prevent javascript from escaping any character within your string values.
// Strings with some data
const domainStr = 'my-domain.com'
const newDomain = 'my-other-domain.com'
// Make sure your string is regex friendly
// This will replace dots for '\'.
const regexUrl = /\./gm;
const substr = `\\\.`;
const domain = domainStr.replace(regexUrl, substr);
// domain is a regex friendly string: 'my-domain\.com'
console.log('Regex expresion for domain', domain)
// HERE!!! You can 'assemble a complex regex using string pieces.
const re = new RegExp( String.raw `([\'|\"]https:\/\/)(${domain})(\S+[\'|\"])`, 'gm');
// now I'll use the regex expression groups to replace the domain
const domainSubst = `$1${newDomain}$3`;
// const page contains all the html text
const result = page.replace(re, domainSubst);
note: Don't forget to use regex101.com to create, test and export REGEX code.
var string = "Hi welcome to stack overflow"
var toSearch = "stack"
//case insensitive search
var result = string.search(new RegExp(toSearch, "i")) > 0 ? 'Matched' : 'notMatched'
https://jsfiddle.net/9f0mb6Lz/
Hope this helps

Regex word search with apostrophe

highlightStr: function (body, searchString){
console.log(searchString);
var regex = new RegExp('(' + searchString + ')', 'gi');
console.log(regex)
return body.replace(regex, "<span class='text-highlight'>$1</span>");
}
Above is the code I'm using. I want to find and replace the searchString, which could be anything. It works fine for most words, but fails when finding words with apostrophes.
How can I modify the regex to include special characters like the appostrophe.
var body = "<br>I like that Apple’s.<br>";
var searchString = "Apple's";
Thank you
You should escape the search string to make sure the regex works OK even if the search string contains special regex metacharacters.
Besides, there is no need wrapping the whole pattern with a capturing group, you may always reference the whole match with $& placeholder from the replacement pattern.
Here is an example code:
var s = "I like that Apple's color";
var searchString = "Apple's";
var regex = new RegExp(searchString.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "gi");
document.body.innerHTML = s.replace(regex, '<b>$&</b>');

Replacing username with profile link javascript

I have this string where there are a bunch of usernames like this -
var someString = "#earth #moon";
And I want the string to be like this -
"[#earth](https://www.somewebsite.com/earth) [#moon](https://www.somewebsite.com/moon)"
I have thought of using regex expressions, but I am not really good in regex
console.log(myStr.replace(/[a-z0-9A-Z-_]/,
"[" + /[a-z0-9A-Z-_]/ +"](https://www.website.com/" + /[a-z0-9A-Z-_]/
);
How to do it?
Assuming you always have the same pattern separated by whitespace, you don't need much of a regex, just split on space and replace the #:
var someString = "#earth #moon";
var str = someString.split(/\s+/).map(item =>
`[${item}](https://www.somewebsite.com/${item.replace('#', '')})`)
.join(" ")
console.log(str)

Remove all content after last '\' is not working

I'm trying to rename a document, I want to remove all the content after the last '\' and then give it another name.
I did it like this but it doesn't seem to be working:
var newDocName = documentPath.replace(/\/$/, '');
var newDocName = newDocName + "\test.pdf";
The '\' doesn't get removed after the first line of code.
Any idea what am I doing wrong?
/\/$/ means you want to match a / if it's the last character in the string meaning this code would replace the very last / if, and only if, it's at the end of the string.
If you want to remove the content after the last \ then you can use a combination of split to split the string on \s then use slice to get everything but the last element. Finally, use join to bring them all back together.
var uri = 'path\\to\\my\\file.ext';
var parts = uri.split('\\');
var withoutFile = parts.slice(0, parts.length - 1);
var putItBackTogether = withoutFile.join('\\');
var voila = putItBackTogether + '\\new-file.name';
console.log(voila);
It is forward slash, use \\ istead.
Try to substitute it for:
var newDocName = documentPath.replace(/\\/$/, '');
Your REGEX has a bad format: you should escape your backquotes (\).
So it may be:
var newDocName = documentPath.replace(/[\\/]$/, '');
var newDocName = newDocName + "\\test.pdf";
This regular expression will search for \ or / at the end ($) of you path. You could use regex101 to test your regular expressions.
You also should consider not using regular expressions when you don’t need them:
var newDocName = documentPath[documentPath.length - 1] == "\\" ? documentPath + "test.pdf" : documentPath + "\\test.pdf";

How to remove the first and the last character of a string

I'm wondering how to remove the first and last character of a string in Javascript.
My url is showing /installers/ and I just want installers.
Sometimes it will be /installers/services/ and I just need installers/services.
So I can't just simply strip the slashes /.
Here you go
var yourString = "/installers/";
var result = yourString.substring(1, yourString.length-1);
console.log(result);
Or you can use .slice as suggested by Ankit Gupta
var yourString = "/installers/services/";
var result = yourString.slice(1,-1);
console.log(result);
Documentation for the slice and substring.
It may be nicer one to use slice like :
string.slice(1, -1)
I don't think jQuery has anything to do with this. Anyway, try the following :
url = url.replace(/^\/|\/$/g, '');
If you dont always have a starting or trailing slash, you could regex it. While regexes are slower then simple replaces/slices, it has a bit more room for logic:
"/installers/services/".replace(/^\/?|\/?$/g, "")
# /installers/services/ -> installers/services
# /installers/services -> installers/services
# installers/services/ -> installers/services
The regex explained:
['start with' ^] + [Optional?] + [slash]: ^/?, escaped -> ^\/?
The pipe ( | ) can be read as or
['ends with' $] + [Optional ?] + [slash] -> /?$, escaped -> \/?$
Combined it would be ^/?|/$ without escaping. Optional first slash OR optional last slash.
Technically it isn't "optional", but "zero or one times".
You can do something like that :
"/installers/services/".replace(/^\/+/g,'').replace(/\/+$/g,'')
This regex is a common way to have the same behaviour of the trim function used in many languages.
A possible implementation of trim function is :
function trim(string, char){
if(!char) char = ' '; //space by default
char = char.replace(/([()[{*+.$^\\|?])/g, '\\$1'); //escape char parameter if needed for regex syntax.
var regex_1 = new RegExp("^" + char + "+", "g");
var regex_2 = new RegExp(char + "+$", "g");
return string.replace(regex_1, '').replace(regex_2, '');
}
Which will delete all / at the beginning and the end of the string. It handles cases like ///installers/services///
You can also simply do :
"/installers/".substring(1, string.length-1);
You can use substring method
s = s.substring(0, s.length - 1) //removes last character
another alternative is slice method
if you need to remove the first leter of string
string.slice(1, 0)
and for remove last letter
string.slice(0, -1)
use .replace(/.*\/(\S+)\//img,"$1")
"/installers/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services
"/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services
It is too nicer shortcode.
response.data.slice(1,-1) // "Prince"
-> Prince
url=url.substring(1,url.Length-1);
This way you can use the directories if it is like .../.../.../... etc.

Categories

Resources