Replace string with a value using RegExp object in javascript [duplicate] - javascript

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Remove all special characters with RegExp
(10 answers)
Closed 3 years ago.
Maybe I forgot how RegExp works but I tried to replace a text with empty values.
I have text like: this is a blabla (32332) [XAML] and I want to remove [] and ().
I want to do using RegExp object. In javascript, I'm doing like:
var obj = "this is a blabla (32332) [XAML]";
var patt1 = "[\(\)\]\[]";
var regObj = new RegExp(patt1, "gi");
obj = obj.replace(regObj, "");
console.log(obj);
The result is still same this is a blabla (32332) [XAML] means nothing is replaced.
Where is my mistake ? Here's fiddle: https://jsfiddle.net/weak5ub3/

You can use capture group and replace
var obj = "this is a blabla (32332) [XAML]";
var patt1 = /\(([^)]*)\)|\[([^\]]*)\]/gi;
obj = obj.replace(patt1, "$1$2");
console.log(obj)
If you want to remove [] and () irrespective of where they are, they are balanced or not, than you can simply use
[\]()\[]+
Regex Demo
using RegExp object, you need is to escape special characters with \\ when you want to use regexp object
var obj = "this is a blabla (32332) [XAML]";
var patt1 = new RegExp("\\(([^)]*)\\)|\\[([^\\]]*)\\]", "gi");
obj = obj.replace(patt1, "$1$2");
console.log(obj)
var pat2 = new RegExp("[\\]()\\[]+", "gi")
var secondObj = obj.replace(pat2, "$1$2")
console.log(secondObj)

Related

Get everything in string after a single comma [duplicate]

This question already has answers here:
How do I split a string with multiple separators in JavaScript?
(25 answers)
How can I convert a comma-separated string to an array?
(19 answers)
Closed 4 years ago.
I have some problem with my string, the variable name is accountcode. I want only part of the string. I want everything in the string which is after the first ,, excluding any extra space after the comma. For example:
accountcode = "xxxx, tes";
accountcode = "xxxx, hello";
Then I want to output like tes and hello.
I tried:
var s = 'xxxx, hello';
s = s.substring(0, s.indexOf(','));
document.write(s);
Just use split with trim.
var accountcode = "xxxx, tes";
var result= accountcode.split(',')[1].trim();
console.log(result);
You can use String.prototype.split():
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
You can use length property of the generated array as the last index to access the string item. Finally trim() the string:
var s = 'xxxx, hello';
s = s.split(',');
s = s[s.length - 1].trim();
document.write(s);
You can use string.lastIndexOf() to pull the last word out without making a new array:
let accountcode = "xxxx, hello";
let lastCommaIndex = accountcode.lastIndexOf(',')
let word = accountcode.slice(lastCommaIndex+1).trim()
console.log(word)
You can split the String on the comma.
var s = 'xxxx, hello';
var parts = s.split(',');
console.log(parts[1]);
If you don't want any leading or trailing spaces, use trim.
var s = 'xxxx, hello';
var parts = s.split(',');
console.log(parts[1].trim());
accountcode = "xxxx, hello";
let macthed=accountcode.match(/\w+$/)
if(matched){
document.write(matched[0])
}
here \w+ means any one or more charecter
and $ meand end of string
so \w+$ means get all the character upto end of the sting
so here ' ' space is not a whole character so it started after space upto $
the if statement is required because if no match found than macthed will be null , and it found it will be an array and first element will be your match

javascript: regex for get string in array of quoted string with separator [duplicate]

This question already has answers here:
Javascript: Split Comma Delimited Quoted Strings
(3 answers)
RegEx to extract all matches from string using RegExp.exec
(19 answers)
Closed 4 years ago.
I have a string like this:
"foo", "bar", "baz"
I want, with a regex, get the single string;
["foo", "bar", "baz"]
This is my code:
var re = new RegExp('"(?:[^"])*"', 'g');
var match = re.exec('"foo", "bar", "baz"');
console.log(match);
but doesn't check for the separator , and return only foo...
You could add brackets and parse the JSON.
var string = '"foo", "bar", "baz"',
array = JSON.parse('[' + string + ']');
console.log(array);
You can choose to use split(/,\s+/) and replace() for that output:
var str = '"foo", "bar", "baz"';
var res = str.split(/,\s+/).map(item=>item.replace(/"/g, ''));
console.log(res);
Here's a solution that chops off the leading/trailing quotes and splits on the delimiter:
const s = '"foo", "bar", "baz"';
console.log(s.slice(1, s.length-1).split('", "'));

Is there a way to replace a string in a text without spaces? [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 6 years ago.
Is there a way to replace something like this:
testHoraciotestHellotest
And replace the 'test' word via javascript, I've tried with the .replace() function but it didn't work
str.replace() also accepts regular expressions, so you can use /test/g to match all instances of 'test' in the string.
var str = "testHoraciotestHellotest";
var res = str.replace(/test/g, "replaced");
console.log(res);
use g to make a global replace to the string
var str = "testHoraciotestHellotest";
var res = str.replace(/test/g, "word");
console.log(res);
It's simple.
var str = "testHoraciotestHellotest";
var res = str.replace("test", "test1");
console.log(res);
If you want to replace all occurances of 'test' rather than just one, use the following trick instead:
var res = str.split("test").join ("test1");

Javascript regex test from variable [duplicate]

This question already has answers here:
Backslashes - Regular Expression - Javascript
(2 answers)
Closed 6 years ago.
I have an problem with constructing regex from variable.
var a = '.playlist-item:nth-child(2n+1)';
var selector = /.playlist-item:nth-child\(2n\+1\)/g;
var s = '.playlist-item:nth-child\(2n\+1\)';
console.log(selector.test(a))//true
var reg = new RegExp(s,"g");
console.log(reg.test(a) )//false
Second is false because I have string quotes around it (I think), how do I construct regexp from string?
https://jsfiddle.net/eq3eu2e8/1/
For a string you have to use double backslashes if you want to include them in the string:
var a = '.playlist-item:nth-child(2n+1)';
var selector = /.playlist-item:nth-child\(2n\+1\)/g;
var s = '.playlist-item:nth-child\\(2n\\+1\\)';
console.log(selector.test(a)); //true
var reg = new RegExp(s,"g");
console.log(reg.test(a)); //false

How to dynamically create regex to use in .match Javascript? [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 8 years ago.
I need to dynamically create a regex to use in match function javascript.
How would that be possible?
var p = "*|";
var s = "|*";
"*|1387461375|* hello *|sfa|* *|3135145|* test".match(/"p"(\d{3,})"s"/g)
this would be the right regex: /\*\|(\d{3,})\|\*/g
even if I add backslashes to p and s it doesn't work. Is it possible?
RegExp is your friend:
var p = "\\*\\|", s = "\\|\\*"
var reg = new RegExp(p + '(\\d{3,})' + s, 'g')
"*|1387461375|* hello *|sfa|* *|3135145|* test".match(reg)
The key to making the dynamic regex global is to transform it into a RegExp object, and pass 'g' in as the second argument.
Working example.
You can construct a RegExp object using your variables first. Also remember to escape * and | while forming RegExp object:
var p = "*|";
var s = "|*";
var re = new RegExp(p.replace(/([*|])/g, '\\$1')
+ "(\\d{3,})" +
s.replace(/([*|])/g, '\\$1'), "g");
var m = "*|1387461375|* hello *|sfa|* *|3135145|* test".match(re);
console.log(m);
//=> ["*|1387461375|*", "*|3135145|*"]

Categories