Remove String Between Substring from RegExp - javascript

I write this code for remove string from 'a' to 'c'
var str = "abcbbabbabcd";
var re = new RegExp("a.*?c","gi");
str = str.replace(re,"");
console.log(str);
The result in console is "bbd"
But the result that right for me is "bbabbd"
Can I use Regular Expression for this Problem ?
Thank for help.

a(?:(?!a).)*c
Use a lookahead based regex.See demo..*? will consume a as well after first a.To stop it use a lookahead.
https://regex101.com/r/cJ6zQ3/34
EDIT:
a[^a]*c
You can actually use negated character class as you have only 1 character.

The g means it's a global regexp, meaning it picks up both the abc and abbabc in the string. So this does properly remove the items from a..c. It seems you saw only two abc and missed the abbabc. The result bbd is actually correct as it does indeed "remove string from 'a' to 'c'".
abcbbabbabcd => bbd

Here is one more way.
var str = "abcbbabbabcd";
var str= str.replace(/abc/g, "");
console.log(str);

You need to update your regex to a[^ac]*?c , this will avoid character a and c between a and c
var str = "abcbbabbabcd";
var re = new RegExp("a[^ac]*?c","gi");
str = str.replace(re,"");
console.log(str);

Related

Remove part of the string before the FIRST dot with js

I have the next problem. I need to remove a part of the string before the first dot in it. I've tried to use split function:
var str = "P001.M003.PO888393";
str = str.split(".").pop();
But the result of str is "PO888393".
I need to remove only the part before the first dot. I want next result: "M003.PO888393".
Someone knows how can I do this? Thanks!
One solution that I can come up with is finding the index of the first period and then extracting the rest of the string from that index+1 using the substring method.
let str = "P001.M003.PO888393";
str = str.substring(str.indexOf('.')+1);
console.log(str)
You can use split and splice function to remove the first entry and use join function to merge the other two strings again as follows:
str = str.split('.').splice(1).join('.');
Result is
M003.PO888393
var str = "P001.M003.PO888393";
str = str.split('.').splice(1).join('.');
console.log(str);
You could use a regular expression with .replace() to match everything from the start of your string up until the first dot ., and replace that with an empty string.
var str = "P001.M003.PO888393";
var res = str.replace(/^[^\.]*\./, '');
console.log(res);
Regex explanation:
^ Match the beginning of the string
[^\.]* match zero or more (*) characters that are not a . character.
\. match a . character
Using these combined matches the first characters in the string include the first ., and replaces it with an empty string ''.
calling replace on the string with regex /^\w+\./g will do it:
let re = /^\w+\./g
let result = "P001.M003.PO888393".replace(re,'')
console.log(result)
where:
\w is word character
+ means one or more times
\. literally .
many way to achieve that:
by using slice function:
let str = "P001.M003.PO888393";
str = str.slice(str.indexOf('.') + 1);
by using substring function
let str = "P001.M003.PO888393";
str = str.substring(str.indexOf('.') + 1);
by using substr function
let str = "P001.M003.PO888393";
str = str.substr(str.indexOf('.') + 1);
and ...

Replace multiple occurences of a comment with javascript

I want to replace multiple occurences of comment and try like below
JsFiddle
Code:
var str = '<!--#test--><!--#test1-->'
str = str.replace('<!--/g', '').replace('-->/g', '');
alert(str)
Your problem is that you're trying to use a string instead of a regular expression. For example, this works.
var str = '<!--#test-->'
str = str.replace(/<!--/g, '').replace(/-->/g, '');
alert(str)
Plain regex commands need to be inside //.
Also, use the
Disjunction; Alternative | (pipe character)
str = str.replace(/<!--|-->/g, ''); // #test#test1

Remove ALL white spaces from text

$("#topNav" + $("#breadCrumb2nd").text().replace(" ", "")).addClass("current");
This is a snippet from my code. I want to add a class to an ID after getting another ID's text property. The problem with this, is the ID holding the text I need, contains gaps between the letters.
I would like the white spaces removed. I have tried TRIM()and REPLACE() but this only partially works. The REPLACE() only removes the 1st space.
You have to tell replace() to repeat the regex:
.replace(/ /g,'')
The g character makes it a "global" match, meaning it repeats the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.
If you want to match all whitespace, and not just the literal space character, use \s instead:
.replace(/\s/g,'')
You can also use .replaceAll if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching all whitespace requires a regex, and when using a regex with .replaceAll, it must be global, so you just end up with extra typing:
.replaceAll(/\s/g,'')
.replace(/\s+/, "")
Will replace the first whitespace only, this includes spaces, tabs and new lines.
To replace all whitespace in the string you need to use global mode
.replace(/\s/g, "")
Now you can use "replaceAll":
console.log(' a b c d e f g '.replaceAll(' ',''));
will print:
abcdefg
But not working in every possible browser:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
Regex for remove white space
\s+
var str = "Visit Microsoft!";
var res = str.replace(/\s+/g, "");
console.log(res);
or
[ ]+
var str = "Visit Microsoft!";
var res = str.replace(/[ ]+/g, "");
console.log(res);
Remove all white space at begin of string
^[ ]+
var str = " Visit Microsoft!";
var res = str.replace(/^[ ]+/g, "");
console.log(res);
remove all white space at end of string
[ ]+$
var str = "Visit Microsoft! ";
var res = str.replace(/[ ]+$/g, "");
console.log(res);
var mystring="fg gg";
console.log(mystring.replaceAll(' ',''))
** 100% working
use replace(/ +/g,'_'):
let text = "I love you"
text = text.replace( / +/g, '_') // replace with underscore ('_')
console.log(text) // I_love_you
Using String.prototype.replace with regex, as mentioned in the other answers, is certainly the best solution.
But, just for fun, you can also remove all whitespaces from a text by using String.prototype.split and String.prototype.join:
const text = ' a b c d e f g ';
const newText = text.split(/\s/).join('');
console.log(newText); // prints abcdefg
I don't understand why we need to use regex here when we can simply use replaceAll
let result = string.replaceAll(' ', '')
result will store string without spaces
let str = 'a big fat hen clock mouse '
console.log(str.split(' ').join(''))
// abigfathenclockmouse
Use string.replace(/\s/g,'')
This will solve the problem.
Happy Coding !!!
simple solution could be : just replace white space ask key value
val = val.replace(' ', '')
Use replace(/\s+/g,''),
for example:
const stripped = ' My String With A Lot Whitespace '.replace(/\s+/g, '')// 'MyStringWithALotWhitespace'
Well, we can also use that [^A-Za-z] with g flag for removing all the spaces in text. Where negated or complemente or ^. Show to the every character or range of character which is inside the brackets. And the about g is indicating that we search globally.
let str = "D S# D2m4a r k 23";
// We are only allowed the character in that range A-Za-z
str = str.replace(/[^A-Za-z]/g,""); // output:- DSDmark
console.log(str)
javascript - Remove ALL white spaces from text - Stack Overflow
Using .replace(/\s+/g,'') works fine;
Example:
this.slug = removeAccent(this.slug).replace(/\s+/g,'');
function RemoveAllSpaces(ToRemove)
{
let str = new String(ToRemove);
while(str.includes(" "))
{
str = str.replace(" ", "");
}
return str;
}

Javascript replace regex wildcard

I have a string which I need to run a replace.
string = replace('/blogs/1/2/all-blogs/','');
The values 1, 2 and all-blogs can change. Is it possible to make them wildcards?
Thanks in advance,
Regards
You can use .* as a placeholder for "zero or more of any character here" or .+ for "one or more of any character here". I'm not 100% sure exactly what you're trying to do, but for instance:
var str = "/blogs/1/2/all-blogs/";
str = str.replace(/\/blogs\/.+\/.+\/.+\//, '');
alert(str); // Alerts "", the string is now blank
But if there's more after or before it:
str = "foo/blogs/1/2/all-blogs/bar";
str = str.replace(/\/blogs\/.+\/.+\/.+\//, '');
alert(str); // Alerts "foobar"
Live example
Note that in both of the above, only the first match will be replaced. If you wanted to replace all matches, add a g like this:
str = str.replace(/\/blogs\/.+\/.+\/.+\//g, '');
// ^-- here
You can read up on JavaScript's regular expressions on MDC.
js> 'www.google.de/blogs/1/2/all-blogs'.replace(/\/blogs\/[^\/]+\/[^\/]+\/[^\/]+\/?/, '');
www.google.de
What about just splitting the string at slashes and just replacing the values?
var myURL = '/blogs/1/2/all-blogs/', fragments, newURL;
fragments = myURL.split('/');
fragments[1] = 3;
fragments[2] = 8;
fragments[3] = 'some-specific-blog';
newURL = fragments.join('/');
That should return:
'/blogs/3/8/some-specific-blog'
Try this
(/.+){4}
escape as appropriate

In Javascript, how can I perform a global replace on string with a variable inside '/' and '/g'?

I want to perform a global replace of string using String.replace in Javascript.
In the documentation I read that I can do this with /g, i.e. for example;
var mystring = mystring.replace(/test/g, mystring);
and this will replace all occurrences inside mystring. No quotes for the expression.
But if I have a variable to find, how can I do this without quotes?
I've tried something like this:
var stringToFind = "test";
//first try
mystring = mystring.replace('/' + stringToFind + '/g', mystring);
//second try, not much sense at all
mystring = mystring.replace(/stringToFind/g, mystring);
but they don't work. Any ideas?
var mystring = "hello world test world";
var find = "world";
var regex = new RegExp(find, "g");
alert(mystring.replace(regex, "yay")); // alerts "hello yay test yay"
In case you need this into a function
replaceGlobally(original, searchTxt, replaceTxt) {
const regex = new RegExp(searchTxt, 'g');
return original.replace(regex, replaceTxt) ;
}
For regex, new RegExp(stringtofind, 'g');. BUT. If ‘find’ contains characters that are special in regex, they will have their regexy meaning. So if you tried to replace the '.' in 'abc.def' with 'x', you'd get 'xxxxxxx' — whoops.
If all you want is a simple string replacement, there is no need for regular expressions! Here is the plain string replace idiom:
mystring= mystring.split(stringtofind).join(replacementstring);
Regular expressions are much slower then string search. So, creating regex with escaped search string is not an optimal way. Even looping though the string would be faster, but I suggest using built-in pre-compiled methods.
Here is a fast and clean way of doing fast global string replace:
sMyString.split(sSearch).join(sReplace);
And that's it.
String.prototype.replaceAll = function (replaceThis, withThis) {
var re = new RegExp(RegExp.quote(replaceThis),"g");
return this.replace(re, withThis);
};
RegExp.quote = function(str) {
return str.replace(/([.?*+^$[\]\\(){}-])/g, "\\$1");
};
var aa = "qwerr.erer".replaceAll(".","A");
alert(aa);
silmiar post
You can use the following solution to perform a global replace on a string with a variable inside '/' and '/g':
myString.replace(new RegExp(strFind, 'g'), strReplace);
Thats a regular expression, not a string. Use the constructor for a RegExp object to dynamically create a regex.
var r = new RegExp(stringToFind, 'g');
mystring.replace(r, 'some replacement text');
Try:
var stringToFind = "test";
mystring = mystring.replace(new RegExp(stringToFind, "g"), mystring);
You can do using following method
see this function:
function SetValue()
{
var txt1='This is a blacK table with BLack pen with bLack lady';
alert(txt1);
var txt2= txt1.replace(/black/gi,'green');
alert(txt2);
}
syntax:
/search_string/{g|gi}
where
g is global case-sensitive replacement
gi is blobal case-insensitive replacement
You can check this JSBIN link
http://jsbin.com/nohuroboxa/edit?html,js,output
If you want variables interpolated, you need to use the RegExp object
https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Regular_Expressions
Example:
var str = "This is my name";
var replace = "i";
var re = new RegExp(replace, 'g')
str = str.replace(re, 'p');
alert(str);
Dynamic global replace
I came to this thread looking for a slightly more complex solution which isn't answered here. I've now found the answer so I'm going to post it in case anyone else finds it useful.
I wanted to do a dynamic global replace, where the replacement strings are based on the original matches.
For example, to capitalise the first letter of all words (e.g. "cat sat mat" into "Cat Sat Mat") with a global find replace. Here's how to do that.
function capitaliseWords(aString) {
// Global match for lowercase letters following a word boundary
var letters = aString.match(/\b[a-z]/g), i, letterMatch;
// Loop over all matched letters
for( i = 0; i < letters.length; i++ ) {
// Replace the matched letters with upper case versions
letterMatch = new RegExp('\\b'+letters[i]); // EDIT - slight fix
aString = aString.replace(letterMatch, letters[i].toUpperCase());
}
// Return our newly capitalised string
return aString;
}
alert( capitaliseWords("cat sat mat") ); // Alerts "Cat Sat Mat"
WIth modern day linters, they prefer you to regEx literal, so rather than new RegExp it would just be `//
With an example:
'test'.replace(/ /gi, '_')
with the test you are looking to replace inside the regex or the /searchableText/ and then replace text in the second parameter. In my case I wanted to replace all spaces with underscores.
Can you use prototype.js? If so you could use String.gsub, like
var myStr = "a day in a life of a thing";
var replace = "a";
var resultString = myStr.gsub(replace, "g");
// resultString will be "g day in g life of g thing"
It will also take regular expressions. To me this is one of the more elegant ways to solve it. prototypejs gsub documentation

Categories