myString.replace( VARIABLE, "") ...... but globally - javascript

How can I use a variable to remove all instances of a substring from a string?
(to remove, I'm thinking the best way is to replace, with nothing, globally... right?)
if I have these 2 strings,
myString = "This sentence is an example sentence."
oldWord = " sentence"
then something like this
myString.replace(oldWord, "");
only replaces the first instance of the variable in the string.
but if I add the global g like this myString.replace(/oldWord/g, ""); it doesn't work, because it thinks oldWord, in this case, is the substring, not a variable. How can I do this with the variable?

Well, you can use this:
var reg = new RegExp(oldWord, "g");
myString.replace(reg, "");
or simply:
myString.replace(new RegExp(oldWord, "g"), "");

You have to use the constructor rather than the literal syntax when passing variables. Stick with the literal syntax for literal strings to avoid confusing escape syntax.
var oldWordRegEx = new RegExp(oldWord,'g');
myString.replace(oldWordRegEx,"");

No need to use a regular expression here: split the string around matches of the substring you want to remove, then join the remaining parts together:
myString.split(oldWord).join('')
In the OP's example:
var myString = "This sentence is an example sentence.";
var oldWord = " sentence";
console.log(myString.split(oldWord).join(''));

According to the docs at MDN, you can do this:
var re = /apples/gi;
var str = 'Apples are round, and apples are juicy.';
var newstr = str.replace(re, 'oranges');
console.log(newstr); // oranges are round, and oranges are juicy.
where /gi tells it to do a global replace, ignoring case.

Related

How can you add e.g. 'gm' to a regex to avoid repeating the full regex again? [duplicate]

I am trying to create something similar to this:
var regexp_loc = /e/i;
except I want the regexp to be dependent on a string, so I tried to use new RegExp but I couldn't get what i wanted.
Basically I want the e in the above regexp to be a string variable but I fail with the syntax.
I tried something like this:
var keyword = "something";
var test_regexp = new RegExp("/" + keyword + "/i");
Basically I want to search for a sub string in a larger string then replace the string with some other string, case insensitive.
regards,
alexander
You need to pass the second parameter:
var r = new RegExp(keyword, "i");
You will also need to escape any special characters in the string to prevent regex injection attacks.
You should also remember to watch out for escape characters within a string...
For example if you wished to detect for a single number \d{1} and you did this...
var pattern = "\d{1}";
var re = new RegExp(pattern);
re.exec("1"); // fail! :(
that would fail as the initial \ is an escape character, you would need to "escape the escape", like so...
var pattern = "\\d{1}" // <-- spot the extra '\'
var re = new RegExp(pattern);
re.exec("1"); // success! :D
When using the RegExp constructor, you don't need the slashes like you do when using a regexp literal. So:
new RegExp(keyword, "i");
Note that you pass in the flags in the second parameter. See here for more info.
Want to share an example here:
I want to replace a string like: hi[var1][var2] to hi[newVar][var2].
and var1 are dynamic generated in the page.
so I had to use:
var regex = new RegExp("\\\\["+var1+"\\\\]",'ig');
mystring.replace(regex,'[newVar]');
This works pretty good to me. in case anyone need this like me.
The reason I have to go with [] is var1 might be a very easy pattern itself, adding the [] would be much accurate.
var keyword = "something";
var test_regexp = new RegExp(something,"i");
You need to convert RegExp, you actually can create a simple function to do it for you:
function toReg(str) {
if(!str || typeof str !== "string") {
return;
}
return new RegExp(str, "i");
}
and call it like:
toReg("something")

Regex or lastIndexOf when removing last instance of a string

I couldn't apply answers to other similar questions (trying to replace the last occurrence of a string) because I am having trouble with the syntax.
I'm trying to replace the last occurrence of a string. The value of the string is stored in a variable that is passed to the .replace() method like this:
var str += some additive strings;
var del = a string that lives within str; // the value is dynamic
str = str.replace(del$, ''); // this doesn't work to remove the last occurrence of `del` in str
As I understand it the $ argument looks for the last occurrence of a string within a regex; but I can't figure out how to use it alongside a variable passed to .replace(). Any suggestions?
If you want to use the RegExp with a $, do it like this:
var str += 'some additive strings';
var re = new RegExp('a string that lives within str$');
str = str.replace(re, '');
str = str.substring(0, str.length - del.length);
You can use lastIndexOf() with slice()
Example:
var str ="HI this is cool isn't it? cool";
var del='cool';// put whatever here
var index = test.lastIndexOf(del);
var length=del.length;
if(index!=-1)
var removeStr=test.substr(index,length);
str.replace(removeStr,''); // HI this is cool isn't it?
Mate, this is just an answer. You'll need to use it according to your needs.
Updated Live demo:http://jsfiddle.net/n2Kgn/2

Simple Javascript string manipulation

I have a string that will look something like this:
I'm sorry the code "codehere" is not valid
I need to get the value inside the quotes inside the string. So essentially I need to get the codehere and store it in a variable.
After some researching it looks like I could loop through the string and use .charAt(i) to find the quotes and then pull the string out one character at a time in between the quotes.
However I feel there has to be a simpler solution for this out there. Any input would be appreciated. Thanks!
You could use indexOf and lastIndexOf to get the position of the quotes:
var openQuote = myString.indexOf('"'),
closeQuote = myString.lastIndexOf('"');
Then you can validate they are not the same position, and use substring to retrieve the code:
var code = myString.substring(openQuote, closeQuote + 1);
Regex:
var a = "I'm sorry the code \"codehere\" is not valid";
var m = a.match(/"[^"]*"/ig);
alert(m[0]);
Try this:
var str = "I'm sorry the code \"cod\"eh\"ere\" is not valid";
alert(str.replace(/^[^"]*"(.*)".*$/g, "$1"));
You could use Javascript's match function. It takes as parameter, a regular expression. Eg:
/\".*\"/
Use regular expressions! You can find a match using a simple regular expressions like /"(.+)"/ with the Javascript RegExp() object. Fore more info see w3schools.com.
Try this:
var msg = "I'm sorry the code \"codehere\" is not valid";
var matchedContent = msg.match(/\".*\"/ig);
//matchedContent is an array
alert(matchedContent[0]);
You should use a Regular Expression. This is a text pattern matcher that is built into the javascript language. Regular expressions look like this: /thing to match/flags* for example, /"(.*)"/, which matches everything between a set of quotes.
Beware, regular expressions are limited -- they can't match nested things, so if the value inside quotes contains quotes itself, you'll end up with a big ugly mess.
*: or new RegExp(...), but use the literal syntax; it's better.
You could always use the .split() string function:
var mystring = 'I\'m sorry the code "codehere" is not valid' ;
var tokens = [] ;
var strsplit = mystring.split('\"') ;
for(var i=0;i<strsplit.length;i++) {
if((i % 2)==0) continue; // Ignore strings outside the quotes
tokens.push(strsplit[i]) ; // Store strings inside quotes.
}
// Output:
// tokens[0] = 'codehere' ;

javascript delete all occurrences of a char in a string

I want to delete all characters like [ or ] or & in a string i.E. :
"[foo] & bar" -> "foo bar"
I don't want to call replace 3 times, is there an easier way than just coding:
var s="[foo] & bar";
s=s.replace('[','');
s=s.replace(']','');
s=s.replace('&','');
Regular expressions [xkcd] (I feel like him ;)):
s = s.replace(/[\[\]&]+/g, '');
Reference:
MDN - string.replace
MDN - Regular Expressions
http://www.regular-expressions.info/
Side note:
JavaScript's replace function only replaces the first occurrence of a character. So even your code would not have replaced all the characters, only the first one of each. If you want to replace all occurrences, you have to use a regular expression with the global modifier.
Today, in 2021 you can use the replaceAll function:
let str = "Hello. My name is John."
let newStr = str.replaceAll('.', '')
console.log(newStr) // result -> Hello My name is John
let nextStr = str.replaceAll('.', '&')
console.log(nextStr) // result -> Hello& My name is John&

how to use a variable in RegExp with search method in Javascript?

I have a string:
var _codes = "1234,1414,5555,3333,2222,5566,4545";
var regex = new RegExp(/1234/i);
var _found = _codes.search(regex);
//this works sofar.
nowi want to do it with variable:
like this:
var id = "1234";
regex = new RegExp("\\"+id+"\\/i");
but it doesn't work. any ideas?
Thanks!
When using the RegExp constructor, you don't supply delimiters and the flags go in the second argument.
var id = "1234";
regex = new RegExp(id, "i");
However, the RegExp just for 1234 with i doesn't really make sense. Use indexOf() instead.
However, perhaps you really did mean to match numbers surrounded with a \. In that case, leave them in there.

Categories

Resources