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
Related
var name = "AlbERt EINstEiN";
function nameChanger(oldName) {
var finalName = oldName;
// Your code goes here!
finalName = oldName.toLowerCase();
finalName = finalName.replace(finalName.charAt(0), finalName.charAt(0).toUpperCase());
for(i = 0; i < finalName.length; i++) {
if (finalName.charAt(i) === " ")
finalName.replace(finalName.charAt(i+1), finalName.charAt(i+1).toUpperCase());
}
// Don't delete this line!
return finalName;
};
// Did your code work? The line below will tell you!
console.log(nameChanger(name));
My code as is, returns 'Albert einstein'. I'm wondering where I've gone wrong?
If I add in
console.log(finalName.charAt(i+1));
AFTER the if statement, and comment out the rest, it prints 'e', so it recognizes charAt(i+1) like it should... I just cannot get it to capitalize that first letter of the 2nd word.
There are two problems with your code sample. I'll go through them one-by-one.
Strings are immutable
This doesn't work the way you think it does:
finalName.replace(finalName.charAt(i+1), finalName.charAt(i+1).toUpperCase());
You need to change it to:
finalName = finalName.replace(finalName.charAt(i+1), finalName.charAt(i+1).toUpperCase());
In JavaScript, strings are immutable. This means that once a string is created, it can't be changed. That might sound strange since in your code, it seems like you are changing the string finalName throughout the loop with methods like replace().
But in reality, you aren't actually changing it! The replace() function takes an input string, does the replacement, and produces a new output string, since it isn't actually allowed to change the input string (immutability). So, tl;dr, if you don't capture the output of replace() by assigning it to a variable, the replaced string is lost.
Incidentally, it's okay to assign it back to the original variable name, which is why you can do finalName = finalName.replace(...).
Replace is greedy
The other problem you'll run into is when you use replace(), you'll be replacing all of the matching characters in the string, not just the ones at the position you are examining. This is because replace() is greedy - if you tell it to replace 'e' with 'E', it'll replace all of them!
What you need to do, essentially, is:
Find a space character (you've already done this)
Grab all of the string up to and including the space; this "side" of the string is good.
Convert the very next letter to uppercase, but only that letter.
Grab the rest of the string, past the letter you converted.
Put all three pieces together (beginning of string, capitalized letter, end of string).
The slice() method will do what you want:
if (finalName.charAt(i) === " ") {
// Get ONLY the letter after the space
var startLetter = finalName.slice(i+1, i+2);
// Concatenate the string up to the letter + the letter uppercased + the rest of the string
finalName = finalName.slice(0, i+1) + startLetter.toUpperCase() + finalName.slice(i+2);
}
Another option is regular expression (regex), which the other answers mentioned. This is probably a better option, since it's a lot cleaner. But, if you're learning programming for the first time, it's easier to understand this manual string work by writing the raw loops. Later you can mess with the efficient way to do it.
Working jsfiddle: http://jsfiddle.net/9dLw1Lfx/
Further reading:
Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
slice() method
You can simplify this down a lot if you pass a RegExp /pattern/flags and a function into str.replace instead of using substrings
function nameChanger(oldName) {
var lowerCase = oldName.toLowerCase(),
titleCase = lowerCase.replace(/\b./g, function ($0) {return $0.toUpperCase()});
return titleCase;
};
In this example I've applied the change to any character . after a word boundary \b, but you may want the more specific /(^| )./g
Another good answer to this question is to use RegEx to do this for you.
var re = /(\b[a-z](?!\s))/g;
var s = "fort collins, croton-on-hudson, harper's ferry, coeur d'alene, o'fallon";
s = s.replace(re, function(x){return x.toUpperCase();});
console.log(s); // "Fort Collins, Croton-On-Hudson, Harper's Ferry, Coeur D'Alene, O'Fallon"
The regular expression being used may need to be changed up slightly, but this should give you an idea of what you can do with regular expressions
Capitalize Letters with JavaScript
The problem is twofold:
1) You need to return a value for finalName.replace, as the method returns an element but doesn't alter the one on which it's predicated.
2) You're not iterating through the string values, so you're only changing the first word. Don't you want to change every word so it's in lower case capitalized?
This code would serve you better:
var name = "AlbERt EINstEiN";
function nameChanger(oldName) {
// Your code goes here!
var finalName = [];
oldName.toLowerCase().split(" ").forEach(function(word) {
newWord = word.replace(word.charAt(0), word.charAt(0).toUpperCase());
finalName.push(newWord);
});
// Don't delete this line!
return finalName.join(" ");
};
// Did your code work? The line below will tell you!
console.log(nameChanger(name));
if (finalName.charAt(i) === " ")
Shouldn't it be
if (finalName.charAt(i) == " ")
Doesn't === check if the object types are equal which should not be since one it a char and the other a string.
I am pulling in a string from another web page. I want to read that string into a variable but only after a certain point. Eg:
#stringexample
var variable;
I want variable to equal stringexample but not contain the # how could I do this?
This is how I am using the variable at the moment.
$("#Outputajax").load("folder/"+ variable +".html");
This is the way that works but isn't a variable.
$("#Outputajax").load("folder/webpage.html");
If you just want to trim of the first character, then you can use substring...
var input = "#stringexample";
input = input.substring(1);
//input = "stringexample"
Here is a working example
var myVariable = stringExample.replace('#','');
Could just use variable.substr(1) to cut off the first character.
If you want to specifically remove the hash from the start (but do nothing if the hash isn't there), try variable.replace(/^#/,"")
I understand you want to get everything in the string AFTER the hashtag. The other solutions will leave anything ahead of the hashtag in as well. And substring does not work if the hashtag is not the first symbol.
variable= "#stringexample".split("#")[1];
This splits the string into an array of strings, with the parameter as the point where to split, without including the parameter itself. There will be an empty string as the first parameter, and everything after the hashtag is the second string.
var slicer = function(somestring){
var parsedString = somestring;
parsedString = parsedString.slice(1);
return parsedString
}
// run from yors function with some string
var someYouVar = slicer("#something")
Any working Regex to find image url ?
Example :
var reg = /^url\(|url\(".*"\)|\)$/;
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
var string2 = 'url(http://domain.com/randompath/random4509324041123213.jpg)';
console.log(string.match(reg));
console.log(string2.match(reg));
I tied but fail with this reg
pattern will look like this, I just want image url between url(" ") or url( )
I just want to get output like http://domain.com/randompath/random4509324041123213.jpg
http://jsbin.com/ahewaq/1/edit
I'd simply use this expression:
/url.*\("?([^")]+)/
This returns an array, where the first index (0) contains the entire match, the second will be the url itself, like so:
'url("http://domain.com/randompath/random4509324041123213.jpg")'.match(/url.*\("?([^")]+)/)[1];
//returns "http://domain.com/randompath/random4509324041123213.jpg"
//or without the quotes, same return, same expression
'url(http://domain.com/randompath/random4509324041123213.jpg)'.match(/url.*\("?([^")]+)/)[1];
If there is a change that single and double quotes are used, you can simply replace all " by either '" or ['"], in this case:
/url.*\(["']?([^"')]+)/
Try this regexp:
var regex = /\burl\(\"?(.*?)\"?\)/;
var match = regex.exec(string);
console.log(match[1]);
The URL is captured in the first subgroup.
If the string will always be consistent, one option would be simply to remove the first 4 characters url(" and the last two "):
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
// Remove last two characters
string = string.substr(0, string.length - 2);
// Remove first five characters
string = string.substr(5, string.length);
Here's a working fiddle.
Benefit of this approach: You can edit it yourself, without asking StackOverflow to do it for you. RegEx is great, but if you don't know it, peppering your code with it makes for a frustrating refactor.
I am pulling content from an RSS feed, before using jquery to format and edit the rss feed (string) that is returned. I am using replace to replace strings and characters like so:
var spanish = $("#wod a").text();
var newspan = spanish.replace("=","-");
$("#wod a").text(newspan);
This works great. I am also trying to remove all text after a certain point. Similar to truncation, I would like to hide all text starting from the word "Example".
In this particular RSS feed, the word example is in every feed. I would like to hide "example" and all text the follows that word. How can I accomplish this?
Though there is not enough jQuery, you even don't need it to remove everything after a certain word in the given string. The first approach is to use substring:
var new_str = str.substring(0, str.indexOf("Example"));
The second is a trick with split:
var new_str = str.split("Example")[0];
If you also want to keep "Example" and just remove everything after that particular word, you can do:
var str = "aaaa1111?bbb&222:Example=123456",
newStr = str.substring(0, str.indexOf('Example') + 'Example'.length);
// will output: aaaa1111?bbb&222:Example
jQuery isn't intended for string manipulation, you should use Vanilla JS for that:
newspan = newspan.replace(/example.*$/i, "");
The .replace() method accepts a regular expression, so in this case I've used /example.*$/i which does a case-insensitive match against the word "example" followed by zero or more of any other characters to the end of the string and replaces them with an empty string.
I would like to hide all text starting from the word "Example"
A solution that uses the simpler replace WITH backreferences so as to "hide" everything starting with the word Example but keeping the stuff before it.
var str = "my house example is bad"
str.replace(/(.*?) example.*/i, "$1") // returns "my house"
// case insensitive. also note the space before example because you
// probably want to throw that out.
I've got a problem with replace not working.
alert($('input#membership_edc').next("label").html().replace(/£/g, ""));
The value of the label after the input would be £24.00, but I want to do a math on that value then put it back with the new value. It's not removing the pound sign.
What's wrong? Thanks.
To read/modify/write use the function parameter version of .html():
$('input#membership_edc').next("label").html(function(index, old) {
var n = parseFloat(old.replace('£', '');
return n + 10;
});
would replace '£24.00' with '34'.
You need to set the value returned from the replace. Try below,
var $label = $('input#membership_edc').next("label");
$label.html($label.html().replace(/£/g, ""));
Nothing wrong. It is working here.
Are you sure your markup is fine?
The string replace function returns a new string. Strings themselves are immutable in javascript, I think. As Vega has it:
// avoid looking this up twice
var label = alert($('input#membership_edc').next("label");
// replace and assign
label.html(label.html().replace(/£/g, ""));
Edit:
To get the numerical value from the string:
var amount = alert($('input#membership_edc').next("label").html().match(/£\s*([-0-9.]+)/)[1];
This matches the numbers etc after the £ (ignoring whitespace), and uses index 1 from the array, containing the contents of the first group match (in the brackets).
" £1.45".match(/£\s*([-0-9.]+)/)[1]; // returns "1.45"
Beware that it is still a string, so you might want to do parseFloat on it.