I just want to write a proper regex to get the source of the image from given html text.
//HTML TEXT: <img src="angry.gif" alt="Angry face" />
var regEx = //regex Here
var source:Object = regEx.exec(htmlText);
var regex:RegEx = /src="(.*?)"/i;
var source:String = regex.exec(htmlText)[1];
var str:String="Content <img src='imagePath01.jpg' width='88' height='88'/> content content content <img src='imagePath01.jpg' width='88' height='88'/>";
var imgRegExp:RegExp = /<img[^>]+>/g;//Get (add 'g' end regex) all img in content;
var imgArr:Array = str.match( imgRegExp );
for(var i:uint=0;i<imgArr.length;i++){
trace(imgArr[i]);
//Get src from img;
var imgXML:XML = XML(imgArr[i]);
trace("src: "+imgXML.#src);
}
Happy code !
Related
Trying to replace text + date just by date using regex, but it not works:
function myfunction() {
var SourceFolder = DriveApp.getFolderById("");
var Files = SourceFolder.getFiles()
var body = DocumentApp.getActiveDocument().getBody();
while(Files.hasNext()) {
var file = Files.next();
body.replaceText("Date: \d{2}.\d{2}.\d{4}", "31.10.2020")
}
}
Thanks
In your code, var body = DocumentApp.getActiveDocument().getBody(); is declared outside of the loop, so you always refer to the active document body in your while loop.
You may use
while(Files.hasNext()) {
var file = Files.next();
var doc = DocumentApp.openById(file.getId());
var body = doc.getBody();
body.replaceText("Date: \\d{2}\\.\\d{2}\\.\\d{4}", "31.10.2020")
}
The point here is to use double backslashes in the pattern, and escape the dot chars since otherwise a . matches any char but a line break char.
function replace_text() {
// Get speadshhet with ID
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Returns cell with ID (User will insert his or her folder ID in cell B3)
var range = sheet.getRange(3, 2);
var values = range.getDisplayValue();
// Get folder by ID - insert your folder ID
var SourceFolder = DriveApp.getFolderById(values);
// Iterate throw all files in folder
var Files = SourceFolder.getFiles();
while(Files.hasNext()) {
var file = Files.next();
// Get all documents ID
var doc = DocumentApp.openById(file.getId());
// Get text body to replace
var body = doc.getBody();
// Insert header in document + alignment
var header = body.insertParagraph(0, 'TEXT');
header.setAlignment(DocumentApp.HorizontalAlignment.RIGHT)
// Text style
var style = {};
//style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;
style[DocumentApp.Attribute.FONT_FAMILY] = 'Arial';
style[DocumentApp.Attribute.FONT_SIZE] = 9;
style[DocumentApp.Attribute.FOREGROUND_COLOR] = '#000000';
body.setAttributes(style)
Logger.log(body)
// Replacing text
body.replaceText("Text", " ");
body.replaceText("Date:\\s*\\d{2}\\.\\d{2}\\.\\d{4}", "31.10.2020")
var paragraphs = body.getParagraphs();
for (var i = 7; i < paragraphs.length; i++) {
var paragraph = paragraphs[i];
paragraph.setAlignment(DocumentApp.Horizontal`enter code here`Alignment.LEFT)
}
}
}
var button = '<button class="btn">Book Now!</button>';
How do I define a value(id) in my a href link?
As Jérôme Teisseire said in a comment, try to edit this in your string
var button = '<a href="test.html?yourid=' + yourid + '" data-ajax="false">
I am trying to play a background video but i am having a problem with one line of code. I get an error that says "Cannot invoke initializer for type 'URL' with no arrangements" At this line "open var contentURL: URL = URL()"
open class VideoSplashViewController: UIViewController {
fileprivate let moviePlayer = AVPlayerViewController()
fileprivate var moviePlayerSoundLevel: Float = 1.0
open var contentURL: URL = URL() {
didSet {
setMoviePlayer(contentURL)
}
}
open var videoFrame: CGRect = CGRect()
open var startTime: CGFloat = 0.0
open var duration: CGFloat = 0.0
open var backgroundColor: UIColor = UIColor.black {
didSet {
view.backgroundColor = backgroundColor
}
}
I don't know how to fix this, please help
The error message is self-explanatory, URL class doesn't have an initializer with no arguments :)
If you take a look at URL class -Hold down CMD key and click on URL-, you will notice that there is no initializer like this:
init() {}
Therefore you can't just write URL() because that requires the above initializer. However, there is a variety of other initializers in URL class such as:
init?(string: String) {}
init(fileURLWithPath path: String)
...
You can use any of them to initialize the contentURL instance.
open var contentURL: URL = URL(string: "") {/**/}
open var contentURL: URL = URL(fileURLWithPath: "") {/**/}
What is Initializer?
You should replace the following code
open var contentURL: URL = URL() {
didSet {
setMoviePlayer(contentURL)
}}
with this:
public var contentURL: NSURL = NSURL() {
didSet {
setMoviePlayer(contentURL)
}}
This will fix your problems.
I have a knockout page where I am formatting the input with regex. It makes the input field to a MM/dd/yyyy format. So if a user inputs "1111" it will change the input vbox to show "01/01/2011" or for "01111" it will show "01/01/2011".
The problem I am facing is that my observable only returning the keystroke entered by user and not the fully formatted item. For example , if user is entering "1111" I get back "1111" instead of the "01/01/2011"
Here is the Html segment
<input id="inpEventDt" placeholder="MM/DD/YYYY" class="input-small" data-date-blur="true" data-regex="^((\d{0,2})|(\d{1,2}/?\d{0,2})|(\d{1,2}/?\d{1,2}/?\d{0,4}))$"
type="text" data-bind="textInput: dateofevent"/>
And this is how I have the knockout binding
var ViewModel = function (eventdt ) {
var self = this;
self.dateofevent = ko.observable(eventdt);
}
viewModel = new ViewModel("");
ko.applyBindings(viewModel);
Trying to figure out what I am doing wrong.
I would not try to format the text input while the user is typing, because it makes a hard to understand user interface and non intuitive typing experience.
In addition, it's more complicated, because while typing, the input is likely invalid.
Try instead to format your input on some event (blur for example), while validating it on keystroke:
var viewModel = function() {
var self = this;
var regex = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
this.isValid = ko.observable(false);
this.date = ko.observable("");
this.format = function() {
self.validate(self.date());
// TODO: something else
}
this.validate = function(newVal) {
var matches = newVal.match(regex);
if (!matches || matches.length != 4) {
self.isValid(false);
} else {
self.isValid(true);
}
};
this.date.subscribe(function(newVal) {
self.validate(newVal);
});
this.style = ko.computed(function() {
return self.isValid() ? "valid" : "invalid";
}, this);
};
var vm = new viewModel();
ko.applyBindings(vm);
.invalid {
border: 1px solid red;
}
.valid {
border: 1px solid green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input id="inpEventDt" placeholder="MM/DD/YYYY" class="input-small" data-date-blur="true" type="text" data-bind="textInput: date, event: { blur: format }, css: style" />
<div data-bind="visible: isValid">OK</div>
You should try using a read/write computed for this. Check out the example 3 in the knockout documentation for computed observables.
Also, here is a jsfiddle using moment.js to help with date formatting.
var ViewModel = function (eventdt ) {
var self = this;
self.dateofevent = ko.observable(eventdt);
self.formattedDate = ko.pureComputed({
read: function () {
return moment(self.dateofevent()).format("MM/DD/YYYY");
},
write: function (value) {
self.dateofevent(moment(value).toDate()); // Write to underlying storage
}
});
}
viewModel = new ViewModel(new Date("03/25/2015"));
ko.applyBindings(viewModel);
I have a very annoying problem. I am developing an RSS Reader for Swift(with Xcode 7.1). i want each cell of my tableview show images for each news. Here is my code:
cell.itemImageView.image = UIImage(named: "placeholder")
let news = items[indexPath.row] as MWFeedItem?
if news?.content != nil {
let htmlContent = news!.content as NSString
var imageSource = ""
let rangeOfString = NSMakeRange(0, htmlContent.length)
let regex = try? NSRegularExpression(pattern: "(<img.*?src=\")(.*?)(\".*?>)", options: [])
if htmlContent.length > 0 {
let match = regex?.firstMatchInString(htmlContent as String, options: [], range: rangeOfString)
if match != nil {
let imageURL = htmlContent.substringWithRange(match!.rangeAtIndex(2)) as NSString
print(imageURL)
if NSString(string: imageURL.lowercaseString).rangeOfString("feedburner").location == NSNotFound {
imageSource = imageURL as String
}
}
}
if imageSource != "" {
cell.itemImageView.setImageWithURL(NSURL(string: imageSource)!, placeholderImage: UIImage(named: "placeholder"))
}
else{
cell.itemImageView.image = UIImage(named: "placeholder")
}
}
So, the problem is that: when the rss feed xml file doesn't have CDATA blocks, my code works perfectly; in other most cases it doesn't work because inside xml file there is a structure like this:
<![CDATA[<p> <img src="http://www.repstatic.it/content/nazionale/img/2015/11/12/115530091-51ce67c2-7b38-41c1-8aa5-21d51b157335.jpg" width="140" align="left" hspace="10">I genitori contro la scelta del consiglio interclasse delle terze elementari dell'istituto Matteotti di fermare la gita all'esposizione "Divina Bellezza" sul...</p>]]></description><guid isPermaLink="true"><!
It's clear that CDATA block doesn't let me read img src link. What can i do?
Thank in advance for your help!
I run the following code in the PlayGround using your regex and successfully got all the img src urls from the xml.
import Foundation
let url = NSURL(string: "http://www.repubblica.it/rss/homepage/rss2.0.xml")!
let xml = try String(contentsOfURL: url)
let regex = try NSRegularExpression(pattern: "(<img.*?src=\")(.*?)(\".*?>)", options: [])
let range = NSMakeRange(0, xml.characters.count)
regex.enumerateMatchesInString(xml, options: [], range: range) { (result, _, _) -> Void in
let nsrange = result!.rangeAtIndex(2)
let start = xml.startIndex.advancedBy(nsrange.location)
let end = start.advancedBy(nsrange.length)
print(xml[start..<end])
}