I have an HTML page with a text box. This text box has an id of "myTextBox". I am trying to use a regular expression in JavaScript to replace certain values in the text box with another value. Currently, I am trying the following
function replaceContent()
{
var tb = document.getElementById("myTextBox");
if (tb != null)
{
var current = new String(tb.value);
var pattern = new RegExp("(ft.)|(ft)|(foot)", "ig");
current = current.replace(pattern, "'");
alert(current);
}
}
Based on this code, if I had the value "2ft" in the myTextBox, I would expect the current variable to be "2'". However, it always shows an empty string. I fear there is something that I am misunderstanding in relation to regular expressions in JavaScript. What am I doing wrong?
Thank you!
Rewrite your pattern to:
(ft\.?|foot|feet)
This will match "ft" or "ft." and "foot" or "feet".
When writing code that uses regular expressions that won't behave, assume (first) that it is your regex that is the problem. Thanks to the compact and esoteric "programming" of regular expressions, it's quite easy to make a mistake you don't see.
If you test the following in Firebug to yield a correct result:
"2ft".replace(/(ft\.?|foot|feet)/ig, "'")
You will get "2'" in your console.
So this answer ought to solve your problem, if the regex is your problem in the first place. Like Rubens said, please check the ID of your textbox and ensure that the item is correctly retrieved.
As The Wicked Flea says, the literal '.' in your regex needs to be escaped. If it's in a character class it can be written un-escaped, but outside of one it must be escaped.
The following works for me:
<script>
var current = "2ft";
var pattern = new RegExp("(ft.)|(ft)|(foot)", "ig");
current = current.replace(pattern, "'");
alert(current);
</script>
Are you sure that tb.value is evaluating properly?
I ran your code using IE8,Chrome and FF3 with no problems.
Please check if your textbox id is correct.
The problem is that you're alternating explicit groupings. Instead you can just do something like the following:
function replaceContent()
{
var tb = document.getElementById("myTextBox");
if (tb != null) {
current = tb.value.replace(/\s*(ft\.|ft|foot|feet)\b/ig, "'");
alert(current);
}
}
Also, note the \s* which will strip leading spaces and the \b which marks the beginning/end of a word. I also added feet.
Related
I have a string of the following form:
data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'>Avatar data
It can be in different languages, but in any case I need to get a string which is between the characters ' '
That is, in the example above, I need to get the following string:
view-7631b26ea80b1b601c313b15cc4e2ab03faedf30
Can I do this using the method string.replace(regexp, str) ?
I've highlighted the desired line using the following regular expression:
/'\b(.*)\b'/gm
Now, using the method string.replace I need to delete everything except that...
Got any suggestions?
Use match method.
var data = "data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'>Avatar data";
data = data.match(/'\b(.*)\b'/gm)
You have good solid anchor text in either side, so:
var match = /data-translate='([^']+)'/.exec(str);
var substr = match && match[1];
Live Example:
var str = "data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'>Avatar data";
var match = /data-translate='([^']+)'/.exec(str);
var substr = match && match[1];
document.body.innerHTML =
"<pre>Got: [" + substr + "]</pre>";
But again, as I said in a comment, using a simple regular expression to extract information from HTML is usually doomed to fail. For instance, you probably don't want to match this:
<p>The string is data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'</p>
...and yet, a simple regex solution will do exactly that. To properly handle HTML, you must use a proper HTML parser.
You can also try this one:
/\'([^\']+)\'/gm
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.
I am trying to write some Javascript to hide some elements that contain only carriage returns. I appreciate that the correct way to solve this problem would be to stop these elements being created, but unfortunately that is not possible in this instance. I am trying to user a regular expression to search for the unwanted elements but am not having much luck. The function I have written is as follows:
function HideEmptyP()
{
var patt = (\\r)
for(var i = 0;i<desc[i].length;i++);
{
var desc[i] = document.getElementsByClassName('sitspagedesc');
var result[i] = patt.test(desc[i]);
if (result[i] == true)
{
desc[i].style.display='none';
}
else
{
alert("No Match!");
}
}
The error I'm getting in the Web Console is 'Syntax Error: Illegal Character'.
Grateful for any ideas on how to solve this.
Thanks in advance.
I am trying to write some Javascript to hide some elements that contain only carriage returns.
There's no need for a regular expression for that, just compare the element's innerHTML property to "\\r", e.g.:
if (demo[i].innerHTML === "\\r") {
// Remove it
}
But beware that some browsers may transform a single carriage return. You might want to check for "\\r", "\\n", and just a space. To do that, you might want to use a regular expression.
Your regular expression literal ((\\r)) is just completely invalid, it's worth reading up on them to learn the correct syntax. To write a regular expression literal in JavaScript, you use / as the delimiter. So: /\\r/. To test that a string contains only \r, \n, or space, you can use /^[\r\n ]+$/ (which requires there be at least one character that matches, and uses ^ to indicate start-of-string, and $ to indicate end-of-string):
if (demo[i].innerHTML.match(/^[\r\n ]+$/) {
// Remove it
}
The reason you are getting Syntax error is because the declaration
var patt = (\r)
is incorrect it should be somethign like var patt = '\r';
Also the whole for loop is wrong.
You should define demo before you start the for loop not inside it, and result need not be an array but just a normal variable
Your litteral seems odd.
Try var patt = /\r/;
var patt=/\n/gi
should work.
extra i flag to denote case insensitive.
g for global search.
I have a string of text "AB-123-2011-07-09", and need to remove everything except "123", then add a "#" sign to the end result.
The string "123" is ever increasing in number, as is the "2011-07-09" (a date). Only "AB" stays the same.
So the end result would be: #123
Is this possible?
Thanks.
EDIT: Just to clarify, I was needing a script that could globally search a page and replace any text which had the format of "AB-xxx-xxxx-xx-xx" with just the digits highlighted here in bold, then adding the "#" before it.
Currently there are only 3 digits in that position, but in the future there may be four.
My code:
function Replace() {
var OldString = "AB-123-2011-07-09";
var NewString = OldString.replace(/^AB-(\d+)-.*/, "#$1");
document.body.innerHTML = document.body.innerHTML.replace(OldString, NewString);
}
window.onload = Replace();
So far it only replaces 1 instance of the string, and uses a fixed string ("AB-123-2011-07-09").
What regular expression do I need to make the 'OldString' dynamic, rather than it being fixed as it is now?
var data = "AB-123-2011-07-09";
var field = data.split('-')[1];
document.write("#" + field);
http://jsfiddle.net/efortis/8acDr/
The following regex would work, but in this case I don't think you need a regex at all (as #Eric has already shown).
"AB-123-2011-07-09".replace(/^AB-(\d+)-.*/, "#$1");
This results in the value #123
http://jsfiddle.net/3XhbE/
Does this work?
var result = mystring.replace(new RegExp(AB-([0-9]+)-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9], "g"),"#$1");
mystring is the "AB-123-2011-07-09" string and result would be "#123".
This is of course possible. This regex would do the trick:
“AB-123-2011-07-09“.replace(/^AB-(\d+)-\d+-\d+-\d+$/, “#$1“);
It also checks you given syntax and that there is nothing else in the string.
migg
Hey all, having an issue doing string replacement for template engine code I am writing. If my tokens are 1 level deep everything works fine. Example {someProperty}. But if I try searching for a nested object it never does the replace. Example {myobj.deep.test}. I've attached the code I am playing around with. Thanks for the help!
function replaceStuff(content, fieldName, fieldValue) {
var regexstr = "{" + fieldName + "}";
console.log("regexstr: ", regexstr);
//var regex = new RegExp("{myobj\.deep\.test}", "g"); //this works as expected
var regex = new RegExp(regexstr, "g"); //this doesn't
return content.replace(regex, fieldValue);
}
replaceStuff("test: {myobj.deep.test}", "myobj.deep.test", "my value");
See this SO question about curly braces. Perhaps your browser of choice isn't as understanding as chrome is?
You need to escape the '.' characters in the string you're passing in as the fieldName parameter. Ditto for any other special regex characters that you want to be interpreted literally. Basically, fieldName is being treated as part of a regex pattern.
If you don't want fieldName to be evaluated as regex code, you might want to consider using string manipulation for this instead.
Edit: I just ran your code in FireFox and it worked perfectly. You may have something else going on here.