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 '
Related
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.
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.
I'm trying to replace more than 1 word in same string, with RegExp, but it seems is not working, i tryied some answers here in stackoverflow, but with no result
var _tpl = "time working $times, not now $times"
var reg = "$times"
var regexp = new RegExp(reg, "g")
var replaceFor = 1
var _newTpl = _tpl.replace(regexp, replaceFor)
console.log(_newTpl)
some advice?
$ is a special character in a regular expression: you must escape it.
var _tpl = "time working $times, not now $times"
var reg = "\\$times"
var regexp = new RegExp(reg, "g")
var replaceFor = 1
var _newTpl = _tpl.replace(regexp, replaceFor)
console.log(_newTpl)
Note that you need two \s in order to put a single literal \ in the resulting string. If you create the regular expression directly, with regex syntax and not string syntax, only use one \:
const regexp = /\$times/g;
You have to escape regex' special characters before passing them to new RegExp.
var reg = "\\$times"
var _tpl = "time working $times, not now $times"
var reg = "\\$times"
var regexp = new RegExp(reg,"g")
var replaceFor = 1
var _newTpl = _tpl.replace(regexp, replaceFor)
console.log(_newTpl)
trying to find every match in a string and process it with a custom function and replace it in the string. When I set text = to the new string though, it never changes, and in the end remains the unchanged.
function submit () {
var searchTerm = document.querySelector('#search-term').value;
var replaceFunction = Function('input', document.querySelector('#function').value);
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
var output = text;
var regex = new RegExp('\d', 'g');
var match, matches = [];
//search for replacements
while ((match = regex.exec(text)) != null) {
var beforeMatch = output.substring(0, match.index);
var afterMatch = output.substring(match.index + match[0].length, text.length);
text = beforeMatch + replaceFunction(match[0]) + afterMatch;
console.log(text);
}
console.log('result', text);
}
function replaceFunction (input) {
return input * 2;
}
You can achieve same result with far less code using replace() and its function's callback that takes match as parameter.
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
text = text.replace(/\d+/g, function(match){
return parseInt(match) * 2;
})
console.log(text)
First of all, you need to use \\ for escape sequence if you are using RegExp constructor. Alternatively you can use the RegExp literal as shown below. Moreover you are using only \d which is going to match a single digit. Instead you should be using \d+ that will match the complete number.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
When using the constructor function, the normal string escape rules
(preceding special characters with \ when included in a string) are
necessary. For example, the following are equivalent:
var re = /\w+/;
var re = new RegExp('\\w+');
Then you are trying to manipulate the string using a loop. Instead simply use replace function as shown below.
function submit () {
// var searchTerm = document.querySelector('#search-term').value;
// var replaceFunction = Function('input', document.querySelector('#function').value);
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
var output = text;
var regex = new RegExp('\\d+', 'g'); // <<<<<< RegExp constructor
// OR
regex = /\d+/g; // <<<<<<< RegExp literal
var match, matches = [];
console.log(text);
output = text.replace(regex, replaceFunction);
console.log('result', output);
}
function replaceFunction (input) {
return parseInt(input) * 2;
}
submit();
Disclaimer: Using RegExp for manipulating HTML elements and attributes is not a good idea and you may end up in unexpected issues if its not used carefully. Use it at your own risk.
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