Regular Expression

var pattern = /(\w+):\/\/([\w.]+)\/(\S*)/i;
var text = "Visit my home page at http://www.wikirex.com/demo.php";
var result = text.match(pattern);

if(result != null){
	var fullurl = result[0];
	var protocol = result[1];
	var host = result[2];
	var path = result[3];
}

Note: Don’t use “g” for pattern or the result won’t be an array

Get parent dir:

function get_dir(url){
	///uploads/cat/icon/normal/glasses_small.jpg
	var pattern = /(.+\/)\w+\.\w{3}$/i;
	var result = url.match(pattern);

	if(result != null){
		return result[1];
	}else{
		return '';
	}
}

Example to replace youtube embed URL:

jQuery(document).ready(function() {
	//Append video params automatically. e.g. autoplay, hide controls.
	$('.flexslider .video').each(function(index){
		var $this = $(this);
		if($this.html() == '') return;

		var code = $this.html();
		var pattern = /<iframe.+src="(.+)"\sframe.+/i;
		var result = code.match(pattern);
		//console.log(result);

		var url = result[1];
		var new_code = code.replace(url, url + '?autoplay=1&showinfo=0&controls=0');
		//console.log(new_code);

		$this.html(new_code);
	});
});

Find not matched expression

// will go to -- 傾印  表格 acer_help.users 結構
\-\-\s傾印\s\s表格\s(?!acer_cms)\.?

Text

-- 傾印  表格 acer_cms.users 結構
-- 傾印  表格 acer_help.users 結構
-- 傾印  表格 acer_help.confluence_content 結構
-- 傾印  表格 buyhelper.bh_orders 結構
-- 傾印  表格 wsdc2017.request 結構

 

One thought on “Regular Expression

  1. Hello there, I discovered your website via Google at the same time as looking for
    a related topic, your website got here up, it seems to be
    great. I’ve bookmarked it in my google bookmarks.
    Hello there, just became aware of your blog through Google, and located that it’s really informative.

    I’m gonna be careful for brussels. I’ll appreciate when you proceed this in future.
    Lots of folks will probably be benefited from your writing.
    Cheers!

Comments are closed.