Replace string between "[]" with javascript using regexp - javascript

I have a string coming back from a webservice the contains open brackets like such "[]"
so the string would look like something like this:
[1] blabh balh blah
I would like to write a regexp that would remove the "[1]" or anything between open brackets.
Right now I've tried something like:
var regexp = /\[[]\\]/g;
but this does not work. I'm stumbling on my own two feet here.
I simply just want to find anything that starts with "[" and ends with "]" and replace everything in the middle including the open and closed brackets.
Any help or guidance would be much appreciated.

This should work:
var str = '[1] blabh balh blah';
str = str.replace(/\[.*?\]\s?/g, '');
If you have nested brackets regexp might no be the best option though.

Is using regexp a requirement? If not, a simple solution might be:
var myString = '[1] Bob Loblaw is the man';
myString = myString.slice(myString.indexOf(']')+1);

Related

String.replace with special characters noting working

I have spent several hours trying to figure out what is going on here looking at stack overflow and elsewhere and I cannot figure out what is going on. I would really appreciate any help!!
I need to make document.write('< /div>'); go to -> < /div>
I've simplified it down to the simplest possible case with the html example below.
<script>
var str = "document.write('</div>');";
str = str.replace("/document.write/g","");
console.log(str); //</div>
</script>
Exclude the quotes and it works. It is being interpreted as a string literal because of the quotes, whereas a regular expression literal is expressed between plain /s.
Also, . needs to be escaped or it matches any other single character.
<script>
var str = "document.write('</div>');";
str = str.replace(/document\.write/g,"");
console.log(str); //</div>
</script>
String.prototype.replace() accepts either a string or a regex. If you are going with a string this should be:
var str = "document.write('</div>');";
str = str.replace("document.write","");
console.log(str);

Replace all braced strings in javascript

i want to make this:
i went to the [open shops], but the [open shops] were closed
look like this:
i went to the markets, but the markets were closed
with javascript replace
im not very good with regex and the square brackets need delimited im sure
Try this:
"i went to the [open shops], but the [open shops] were closed".replace(/\[open shops\]/g, 'markets');
The tricky part is the the need to escape the brackets and add the global match to replace each matching instance. For more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
All you need to do is put \ before [ and ] to treat it as a regular character. This way your regex would become \[openshops\].
If you have multiple things that need to be replaced (eg. [shops] and [state]) you can do the following which dynamically creates the regex. This way you don't have to hard code it for each thing.
var str = "I went to the [shops], but the [shops] were [state]. I hate it when the [shops] are [state].";
var things = {
shops: "markets",
state: "closed"
};
for (thing in things) {
var re = new RegExp("\\["+thing+"\\]", "g");
str = str.replace(re, things[thing]);
}
console.log(str);
Note that you need to use two backslashes instead of just one when doing it this way.
If you don't want to use regex. You could use something like.
var a = "i went to the [open shops], but the [open shops] were closed";
var replacement = "KAPOW!";
while(a.contains("[") && a.contains("]"))
{
var left = a.indexOf("[");
var right = a.indexOf("]");
a = a.substring(0,left) + replacement + a.substring(right+ 1);
}
console.log(a);

RegEx for WordPress file

I am trying to recognize a string like this one: file=2013/08/something_320x480.jpg and to replace it in JavaScript.
Here is my regex:
newStr = str.replace('/file=\d+\/\d+\/.+\d+x\d+.jpg/', 'irrelevant');
I also tried
newStr = str.replace('/file=.+\.jpg/', 'irrelevant');
However, my string is never replaced. What am I doing wrong?
The regexp literal does not take apostrophes.
Try:
newStr = str.replace(/file=\d+\/\d+\/.+\d+x\d+.jpg/, 'irrelevant');
Are you sure the file is set as you say it is? I just tried your example in the console and it works...
> var a = "file=2013/08/something_320x480.jpg"
undefined
> a.replace(/^file=\d+\/\d+\/.+\d+x\d+.jpg$/, 'irrelevant');
"irrelevant"
Update: I didn't spot that you had apos' in your regex, well spotted #Taemyr

regex replace in javascript/jquery

I've never really used regex so this is probably a basic question, but I need to reformat a string in javascript/jquery and I think regex is the direction to go.
How can I convert this string:
\"1\",\"2\",\"\\",\"\4\"
into:
"1","2","","4"
These are both strings, so really they'd be contained in "" but I thought that may confuse things even more.
I've tried the following but it doesn't work:
var value = '\"1\",\"2\",\"\\",\"\4\"'.replace(/\"/, '"').replace(/"\//, '"');
Try:
var value = your_string.replace(/\\/g, "");
to remove all the "\"
It's a lot of escaping... Your string is:
var str = '\\"1\\",\\"2\\",\\"\\\\",\\"\\4\\"'
console.log(str.replace(/\\/g, '')) // "1","2","","4"
However, if you want only to replace \" with " use:
console.log(str.replace(/\\"/g, '"')) // "1","2","\","\4"

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' ;

Categories

Resources