how to get special character from string in nodejs and replace - javascript

how to find specific special character from string and replace it to unicode \u0026 + = \u002B
replace only these special character : [$, &, +, #]
example : "HELLO JAMES (WITH ME YOUR) \n+++ SEE & FIELD 4-B +++
MY code
var char = '+';
var saa =char.charCodeAt(0);
console.log(saa)
var codeHex = saa.toString(16).toUpperCase();
while (codeHex.length < 4) {
codeHex = "0" + codeHex;
}
var afteruni = name.replaceAll('\+','\\u'+codeHex)
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
i want like this :
"HELLO JAMES (WITH ME YOUR) \n\u002B\u002B\u002B SEE \u0026 FIELD 4-B
\u002B\u002B\u002B"
ERROR : Invalid regular expression: /+/: Nothing to repeat\

you don't need to redefined replaceAll - why do that? replaceAll will already give you a correct response :
just replace line: var afteruni = name.replaceAll('\+','\\u'+codeHex)
with var afteruni = name.replaceAll(/\+/g,'\\u'+codeHex)
iv'e run that in my PC and it is working.

Related

How can get phrases from a string with regular expressions

How could I get from the string only the texts text_add () for_delete () this_edit ()
and leave them in an array.
I try to occupy a regular expression and filter by the data of the array and it doesn't work for me.
Who can help me?
let filter=["_add()","_delete()","_edit()"];
var cadena="text_add()-----for_delete()___ this_edit() this example is a test hello world";
var myMethod = new RegExp('(\\w*' + filter + '\\w*)', 'gi');
var matchesMethod = r.match(myMethod);
if (matchesMethod != null) {
arrayMethod.push(matchesMethod.toString().split(","));
}
try :
var cadena="text_add()-----for_delete()___ this_edit() this example is a test hello world";
var arr = cadena.match(/(\w*\(\))/g);
\w : Matches any word character (alphanumeric & underscore).
* : Match 0 or more characters.
\( : Matches a "(" character.
\) : Matches a ")" character.
g : global flag
here demo

JavaScript - Get only a part of the string after a particular expression

I have the following:
var string = 'https://sub.example.com/dir/ https://sub.example.com/dir/v2.5/'
var hostname = 'sub.example.com';
var hostname_match = hostname.replace(/\./g, '\\.');
string.replace(new RegExp('https\:\/\/'+hostname_match+'\/(.*)', 'g'), '/$1');
What I want is to get the following :
/dir/ /dir/v2.5/
You can just replace the http:// + hostname:
var string = 'https://sub.example.com/dir/ https://sub.example.com/dir/v2.5/'
var hostname = 'sub.example.com';
let urls = string.split(' ')
.map(u => u.replace('https://'+hostname, ''))
console.log(urls)
// if you want a space-separated string:
console.log(urls.join(' '))
You may use
new RegExp('https://'+hostname_match+'/(\\S*)', 'g')
Here, .* is replaced with \S* matching zero or more non-whitespace characters.
See JS demo:
var string = 'https://sub.example.com/dir/ https://sub.example.com/dir/v2.5/'
var hostname = 'sub.example.com';
var hostname_match = hostname.replace(/\./g, '\\.');
console.log(
string.replace(new RegExp('https://'+hostname_match+'/(\\S*)', 'g'), '/$1')
);
Note that you do not need to escape forward slashes in the constructor notation, as / is not a special regex metacharacter. The colon does not have to be escaped in any regex contexts.

Regular Expression: replace string in javascript

I want a regular expression to match a string like this "(192)"
the string starts with "(" and ends with ")" and numbers from 0 to 9 go between the parentheses.
I've tried this function before but it does not work:
function remove_garbage_numbers(str) {
var find = '^\([0-9]\)$';
var re = new RegExp(find, 'g');
return str.replace(re, '');
}
You don't need to pass this to RegExp constructor. And you don't need to have a g modifier when anchors are used. And aso when anchors are used, it's safe to use m multiline modifier.
var find = /^\([0-9]+\)$/m;
ie,
function remove_garbage_numbers(str) {
var re = /^\([0-9]+\)$/m;
return str.replace(re, '');
}
OR
var re = new RegExp("^\\([0-9]+\\)$", 'm');
ie,
function remove_garbage_numbers(str) {
var re = new RegExp("^\\([0-9]+\\)$", 'm');
return str.replace(re, '');
}
Update
> "Main (191)|Health & Beauty (6)|Vision Care (8)".replace(/\(\d+\)/g, "")
'Main |Health & Beauty |Vision Care '

Use dynamic (variable) string as regex pattern in JavaScript

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

Javascript Trim as is in C#

There is JQuery.trim() function but it is trimming the white spaces.
But I want to do it like in C#.
string props = ",width=400,height=400,status=0,location=0,";
props.Trim(',');
// result will be: "width=400,height=400,status=0,location=0"
How can I do this? Actually I would like to use it for general input param not only for ','..
Try an regexp:
var props=",width=400,height=400,status=0,location=0,";
props=props.replace(/^[,]*(.*?)[,]*$/, "$1");
If you, for example, also want to remove semicolons at the beginning or the end, use this:
props=props.replace(/^[,;]*(.*?)[,;]*$/, "$1");
And if you want to remove spaces, too, but only at the end:
props=props.replace(/^[,;]*(.*?)[,; ]*$/, "$1");
I found a link do this with functions and I found another link how to add this function to the String type. And I wrote below code and its test link :
String.prototype.TrimLeft = function (chars) {
//debugger;
var re = chars ? new RegExp("^[" + chars + "]+/", "g")
: new RegExp(/^\s+/);
return this.replace(re, "");
}
String.prototype.TrimRight = function (chars) {
var re = chars ? new RegExp("[" + chars + "]+$/", "g")
: new RegExp(/\s+$/);
return this.replace(re, "");
}
String.prototype.Trim = function (chars) {
return this.TrimLeft(chars).TrimRight(chars);
}
^[" + chars + "]+ is finding the characters at the begining of string.
And it is replacing on this line: this.replace(re, "");
With this : [" + chars + "]+$, it is searching characters at the end of string g(globally) and replacing with the same method.
var c=",width=400,height=400,status=0,";
c.Trim(",");
// result: width=400,height=400,status=0

Categories