jQuery / Javascript replace multiple occurences not working - javascript

I'm trying to replace multiple occurrences of a string and nothing seems to be working for me. In my browser or even when testing online. Where am I going wrong?
str = '[{name}] is happy today as data-name="[{name}]" won the match today. [{name}] made 100 runs.';
str = str.replace('/[{name}]/gi','John');
console.log(str);
http://jsfiddle.net/SXTd4/
I got that example from here, and that too wont work.

You must not quote regexes, the correct notation would be:
str = str.replace(/\[{name}\]/gi,'John');
Also, you have to escape the [], because otherwise the content inside is treated as character class.
Updating your fiddle accordingly makes it work.
There are two ways declaring regexes:
// literal notation - the preferred option
var re = /regex here/;
// via constructor
var re = new Regexp('regex here');

You should not put your regex in quotes and you need to escape []
Simply use
str = str.replace(/\[{name}\]/gi,'John');
DEMO

While there are plenty of regex answers here is another way:
str = str.split('[{name}]').join('John');

The characters [ ] { } should be escaped in your regular expression.

Related

Unable to replace a substring in a string

I can't replace the substring in a string:
var source = "div.col-md-4.fields:visible:eq(0) div.panel-body select:eq(0)";
var modified = source.replace(/visible:eq(0)/g, "1234");
I wonder why does modified have the same value as source?
You should not use regular expressions here but a simple string replace function. It will run faster and regular expressions were not made for simple tasks like this as they will run slightly slower than the simple replace function. Using regular expressions here is like using a nuke to open a water bottle, rather prefer simplicity, if a developer sees this code he will like the simplicity.
Change your second line to this one:
var modified = source.replace("visible:eq(0)", "1234");
You need to escape the brackets
var source = "div.col-md-4.fields:visible:eq(0) div.panel-body select:eq(0)";
var modified = source.replace(/visible:eq\(0\)/g, "1234");
console.log(source);
console.log(modified);
You just need to escape your chars like this Demo: http://jsfiddle.net/cvW24/1/
hope rest help the cause :)
if you keen:
Need to escape a special character in a jQuery selector string
http://api.jquery.com/category/selectors/
code
var source = "div.col-md-4.fields:visible:eq(0) div.panel-body select:eq(0)";
var modified = source.replace(/visible:eq\(0\)/g, "1234");
alert(modified);
Because your regular expression does not match the string. You need to escape the parenthesis.
var modified = source.replace(/visible:eq\(0\)/g, "1234");

How to match a specific regular expression?

I am having a hard time understanding how to match a certain regular expression using javascripts match() function. I have a field in a table stored in the following format:
CH-01-Feb-13-1. I want to be able to grab the date without the dashes, i.e. 01-Feb-13. I was trying to figure out how to combine with ^- or . but not sure how to do it.
So you want the regular expression?
Something like
^\w{2}-(\d{2}-\w{3}-\d{2}).*?$
You can see the explanation here: http://www.regexper.com/ Just copy and paste the expression.
Example with Javascript
var r = /^\w{2}-(\d{2}-\w{3}-\d{2}).*?$/i
var groups = "CH-01-Feb-13-1".match(r);
console.log(groups);
If you are not comfortable with Regex then you can use something like this.
var str = 'CH-01-Feb-13-1';
str = str.replace('CH-','');
str = str.split('-');
str.pop();
console.log(str.join('-'));

Javascript regex expression to replace multiple strings?

I've a string done like this: "http://something.org/dom/My_happy_dog_%28is%29cool!"
How can I remove all the initial domain, the multiple underscore and the percentage stuff?
For now I'm just doing some multiple replace, like
str = str.replace("http://something.org/dom/","");
str = str.replace("_%28"," ");
and go on, but it's really ugly.. any help?
Thanks!
EDIT:
the exact input would be "My happy dog is cool!" so I would like to get rid of the initial address and remove the underscores and percentage and put the spaces in the right place!
The problem is that trying to put a regex on Chrome "something goes wrong". Is it a problem of Chrome or my regex?
I'd suggest:
var str = "http://something.org/dom/My_happy_dog_%28is%29cool!";
str.substring(str.lastIndexOf('/')+1).replace(/(_)|(%\d{2,})/g,' ');
JS Fiddle demo.
The reason I took this approach is that RegEx is fairly expensive, and is often tricky to fine tune to the point where edge-cases become less troublesome; so I opted to use simple string manipulation to reduce the RegEx work.
Effectively the above creates a substring of the given str variable, from the index point of the lastIndexOf('/') (which does exactly what you'd expect) and adding 1 to that so the substring is from the point after the / not before it.
The regex: (_) matches the underscores, the | just serves as an or operator and the (%\d{2,}) serves to match digit characters that occur twice in succession and follow a % sign.
The parentheses surrounding each part of the regex around the |, serve to identify matching groups, which are used to identify what parts should be replaced by the ' ' (single-space) string in the second of the arguments passed to replace().
References:
lastIndexOf().
replace().
substring().
You can use unescape to decode the percentages:
str = unescape("http://something.org/dom/My_happy_dog_%28is%29cool!")
str = str.replace("http://something.org/dom/","");
Maybe you could use a regular expression to pull out what you need, rather than getting rid of what you don't want. What is it you are trying to keep?
You can also chain them together as in:
str.replace("http://something.org/dom/", "").replace("something else", "");
You haven't defined the problem very exactly. To get rid of all stretches of characters ending in %<digit><digit> you'd say
var re = /.*%\d\d/g;
var str = str.replace(re, "");
ok, if you want to replace all that stuff I think that you would need something like this:
/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g
test
var string = "http://something.org/dom/My_happy_dog_%28is%29cool!";
string = string.replace(/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g,"");

Regular Expression - Search and Replace

I'm new to regular expression and have come across a problem.
I want to do a search and replace on a string.
Search for an instance of -- and ' and replace it with - and `, respectively.
Example
Current String: Hi'yo every--body!
Replaced String: Hi`yo every-body!
Any help would greatly be appreciated!
You need.
"Hi'yo every--body!".replace(/--/g, '-').replace(/'/,'`')
Make a function
function andrew_styler(s){return s.replace(/--/g, '-').replace(/'/,'`');}
If you want just replace -- with - use the simplest regexp:
var str = "Hi'yo every--body!";
str = str.replace(/--/g, '-');
The flag g turns the global search on, so that pattern replace all occurances.
#dfsq is correct, regexp is overkill for a couple of simple replaces but for reference.
var s = "Hi'yo every--body!";
s = s.replace(/'/g, "`").replace(/\-{2}/g, "-");

Help with a regular expression to capture numbers

I need to capture the price out of the following string:
Price: 30.
I need the 30 here, so I figured I'd use the following regex:
([0-9]+)$
This works in Rubular, but it returns null when I try it in my javascript.
console.log(values[1]);
// Price: 100
var price = values[1].match('/([0-9]+)$/g');
// null
Any ideas? Thanks in advance
Try this:
var price = values[1].match(/([0-9]+)$/g);
JavaScript supports RegExp literals, you don't need quotes and delimiters.
.match(/\d+$/) should behave the same, by the way.
See also: MDN - Creating a Regular Expression
Keep in mind there are simpler ways of getting this data. For example:
var tokens = values[1].split(': ');
var price = tokens[1];
You can also split by a single space, and probably want to add some validation.
Why don't you use this?
var matches = a.match(/\d+/);
then you can consume the first element (or last)
my suggestion is to avoid using $ in the end because there might be a space in the end.
This also works:
var price = values[1].match('([0-9]+)$');
It appears that you escaped the open-perens and therefore the regex is looking for "(90".
You don't need to put quotes around the regular expression in JavaScript.

Categories