JS or Prototype: Break string into two variables
Say I have a load of strings that follow the same sort of struct开发者_如何学Cure as this:
Outcome 1: - Be able to create 2D animations for use as part of an interactive media product.
I want to get everything before the '-' and put it into one variable, and everything after the '-' and put it into another variable. So output is as so:
$1 = "Outcome 1";
$2 = "Be able to create 2D animations for use as part of an interactive media product.";
Thanks
(Also does anyone know how I would then remove the title tag from the following selector?
$$('span[title]').each(function(element) {
});
You can split a string using regular expressions. In your case, you want to:
- Get rid of the colon (:)
- Get rid of the extra space surrounding the dash (-)
So:
var tokens = s.split(/:\s*-\s*/);
// tokens[0] will be the first part
// tokens[1] the second
var string = "Outcome 1: - Be able to create 2D animations for use as part of an interactive media product."
var strArr = string.split("-");
RESULTS:
strArr[0] == "Outcome 1: "
strArr[1] == " Be able to create 2D animations for use as part of an interactive media product."
Fiddle: http://jsfiddle.net/maniator/VqcPJ/
This regex will remove the trailing colon on the first element and any whitespace surrounding the dash as well:
var parts = str.split(/\s*:\s*-\s*/);
parts; // => ['Outcome 1', 'Be able to create...']
精彩评论