Javascript replace using regular expression - javascript

I need replace url from a string.
example:
var container = "hello http://www.youtube.com/watch?v=r94hrE10S84 hello";
I want replace to:
container = "hello <iframe src='//www.youtube.com/embed/r94hrE10S84' </iframe> guys";
Im trying to do:
container = container.replace("http://www.youtube.com/watch?v=(/\w*\d+\w*/)","<iframe src='//www.youtube.com/embed/$1' </iframe>");
thank you

container.replace(/(https?:\/\/\S+)/i, "<iframe src='$1' </iframe>");

You can use:
repl = container.replace(/(https?:\/\/\S+)/i, function(m) {
if (m.indexOf(".youtube."))
return m.replace(/^(.+?)\/watch\?v=(.+)$/, "<iframe src='$1/embed/$2'> </iframe>");
else return m;
});
//=> ello <iframe src='http://www.youtube.com/embed/r94hrE10S84'> </iframe> hello

(?:https?://)?(?:www\.)?youtu(?:be\.com/watch\?(?:.*?&(?:amp;)?)?v=|\.be/)([\w‌​\-]+)(?:&(?:amp;)?[\w\?=]*)?
ID Should be on first group.
So your code will be like:
var container = "http://www.youtube.com/watch?v=r94hrE10S84";
var reg = /(?:https?:\/\/)?(?:www\.)?youtu(?:be\.com\/watch\?(?:.*?&(?:amp;)?)?v=|\.be\/)([\w‌​\-]+)(?:&(?:amp;)?[\w\?=]*)?/;
container = container.replace(reg,"<iframe src=\"//www.youtube.com/embed/$1\"></iframe>");
This take into account even link w/o www, w/o protocol and short links (youtu.be)
Fiddle
Source

Related

Regex to remove dash and everything after it

I've got a function to remove the dash and everything that comes after it from a title.
This is the JS
<script>
(function() {
var str2 = document.querySelector('.dash-remove').innerHTML;
var txt2 = str2.replace(/ -.*$/g,"");
document.querySelector('.dash-remove').innerHTML = txt2;
})();
</script>
The Html is something like this
<h2 class="dash-remove">Testing - this function</h2>
However this isn't working, it's not removing the dash or the text after.
I've tried just removing the dash like this:
<script>
(function() {
var str2 = document.querySelector('.dash-remove').innerHTML;
var txt2 = str2.replace('-',"");
document.querySelector('.dash-remove').innerHTML = txt2;
})();
</script>
And this works so I assume it's something to do with the regex? any ideas?
As discussed in OP's comments, this may be due to the class being present multiple times. You should then use document.querySelectorAll along with NodeList#forEach :
(function() {
document.querySelectorAll('.dash-remove').forEach(item => {
item.innerHTML = item.innerHTML.replace(/ -.*$/g, '');
});
})();
The Html is something like this
<h2 class="dash-remove">Testing - this function</h2>
<h2 class="dash-remove">Testing - that function</h2>

How to extract content of html tags from a string using javascript or angularjs?

I have a string containing content in some html tags and also some text alone.
It looks like this :
var str = "<p></p><p><i>blabla</i></p><p><i><b>blaaaaaablaaaaa</b></i></p><iframe src="..." height="111" width="333"></iframe><p></p><p><sub>hello blabla</sub></p><p><br></p><iframe src="..." height="444" width="888"></iframe>"
I would like to extract somehow in Javascript or AngularJS only some tag (including content and attributes) then put them into an array.
For example, if I want only <iframe> tag, I should have this :
var array = ["<iframe src='...' height='111' width='333'></iframe>", "<iframe src='...' height='444' width='888'></iframe>"];
If I want <p> tag then :
var array = ["", "<i>blabla</i>","<i><b>blaaaaaablaaaaa</b></i>","","<sub>hello blabla</sub>","<br>"];
Any suggestion ? Thanks !
NOTE : Don't give an answer using Jquery please !
You could create an angular element and get the text out of it.
Example:
$scope.array =[];
$scope.eles=
angular.element(str).find('iframe');
[].forEach.call($scope.eles, function (ctl) {
$scope.name.push(angular.element(ctl).text())
});
here is a demo: http://jsfiddle.net/Lvc0u55v/5122/
Edit
To get all the html of the tag you can do:
angular.element(str).find('iframe');
[].forEach.call($scope.eles, function (ctl) {
$scope.name.push(ctl.outerHTML)
});
demo: http://jsfiddle.net/Lvc0u55v/5123/
try this code:
var iFrameArr= str.match("<iframe>(.*)<iframe>");
var iFrameContent = iFrameArr[1];
You will want to look at splitting up the string with regex using a filter such as '(<iframe>).*(<\/iframe>)'. This will find the tags of and as well as everything in between, putting it into a capture group per iteration found.
Set the html content to the DOM and extract the iframe tag using jquery
Assuming you have a div with id='test' in your DOM
var str = "<div> .... </div> <iframe src=".....">..</iframe>
text blabla
<iframe src="....."> ....blabla2.... </iframe>
....
<p>.....</p>
......";
$('#test').html(str);
var ar=[]
$('#test iframe').each(function() {
var x = $(this).wrap('<p/>').parent().html();//wrap the iframe with element p and get the html of the parent
ar.push(x)//add the html content to array
});
//now ar contains the expected output

How to strip specific tag into div in Javascript?

I have this html code
<div class="myDiv">
My link
<p>This is a paragraph</p>
<script>//This is a script</script>
</div>
And I this javascript:
$('.myDiv').children().each(
function() {
var strToStrip = $('.myDiv').html();
if ( this.tagName != 'A' ) {
// Strip tag element if tagName is not 'A'
// and replace < or > with < or >
strToStrip.replace(/(<([^>]+)>)(?!(a))/ig, "");
}
}
);
How can I strip all tags, except from the a element?
I only need the link and strip tags if it is not a link tag.
I can't find what wrong with this code and what regex can I use to do this.
Any help please?
Try this regex example:
var strToStrip = $('.myDiv').html();
var temp = strToStrip.replace(/<[^a\/][a-z]*>/g, "<");
var result = temp.replace(/<\/[^a][a-z]*>/g, ">");
alert(result);
My goal of this question is to figure out how twitter do his hashtag or usergroup by using # or #. Go here to see the final result
you can use replace method of string using regular expr
var html = $("#main").html();
var result = html.replace(/[\<\>\/]/g,'');
alert(result);
the example shown here

Javascript regexp match doesn't work

var code = '{html}here is html code{/html}{css}here is css code{/css}';
var preg = code.match(new RegExp(/\{.*?\}(.*?)\{\/.*?\}/g));
console.log(preg[1][0]);
Result: {.
How to output "here is html code" and "here is css code"?
jsfiddle: http://jsfiddle.net/cqr3K/
Another way to get all submatches.
var code = '{html}here is html code{/html}{css}here is css code{/css}';
var re = /[^}]+(?=\{)/g;
var match;
while (match = re.exec(code)) {
console.log(match[0]);
}
Output
here is html code
here is css code
You can do this:
var code = '{html}here is html code{/html}{css}here is css code{/css}';
var preg = code.replace(/\{.*?\}(.*?)\{\/.*?\}/g, function (match,group) {
console.log(group);
return "";
});
You can do that as follows:
/\}(.*?)\{/g
The first captured group $1 is what you want. It will contain here is html code and here is css code
Demo: http://regex101.com/r/yC7lD7

Escape characters in String in a HTML page?

I have a string in the below non-escaped format in a HTML page:
<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>
What I need is to use jQuery/JavaScript to replace that string with just the link "SomeThing".
I have looked at some examples in StackOverflow, but they don't seem to work. I'm just getting started with jQuery and JavaScript, so would appreciate any help here.
Any ideas?
Try html() and text() in jquery to decode:
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var decoded = $('<div />').html(str).text();
alert($(decoded).text());
See Fiddle demo
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var helper = document.createElement('p');
// evaluate as HTML once, text now "<a href..."
helper.innerHtml = str;
// evaluate as HTML again, helper now has child element a
helper.innerHtml = helper.innerText;
// get text content only ("SomeThing")
alert(helper.innerText);
Here is a possible starting point.
Hope this gets you started!
function parseString(){
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var begin = str.indexOf('\">',0)+2; //--determine where the opening anchor tag ends
var end = str.indexOf('</a>',0); //--determine where the closing anchor tag begins
var parsedString = str.substring(begin,end); //--grab whats in between;
/*//--or all inline
var parsedString = str.substring(str.indexOf('\">',0)+2,str.indexOf('</a>',0));
*/
console.log(parsedString);
}
parseStr();

Categories