Replace substring in all lines in textarea using javascript - javascript

Am trying to replace a particular string from all lines using javascript. Here is sample
www.youtube.com/watch?v=s8IJkexsjlI&index=37&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=PYOQLPW6ewQ&index=38&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=ejRmaOHs1rk&index=39&list=PLB03EA9545DD188C3
I want to replace the 11 characters after '=' how can I do it with a variable
like var= 'hello123456'
so output will be
www.youtube.com/watch?v=hello123456&index=37&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=hello123456&index=38&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=hello123456&index=39&list=PLB03EA9545DD188C3

Here is regex solution, see the snippet below
document.addEventListener("DOMContentLoaded", function(){
var link = "www.youtube.com/watch?v=s8IJkexsjlI&index=37&list=PLB03EA9545DD188C3";
var value = "hello123456";
link = link.replace(/\?v=(.*)\&index/g, "?v="+value+"&index")
document.getElementById("id").innerHTML = link
});
Input link:
<div>www.youtube.com/watch?v=s8IJkexsjlI&index=37&list=PLB03EA9545DD188C3</div>
<br>
<br>
Output link:
<div id="id"></div>

Please check the below code
var youstr="www.youtube.com/watch?v=s8IJkexsjlI&index=37&list=PLB03EA9545DD188C3";
var start=youstr.indexOf("=");
var end=start+11;
var replaceStr=youstr.slice(start,start+11);
youstr=youstr.replace(replaceStr,"ReplaceString");

This is pretty straightforward solution, without any fanciness so you could easy understand what's happening.
var originalStr = 'www.youtube.com/watch?v=s8IJkexsjlI&index=37&list=PLB03EA9545DD188C3';
var textToReplaceWith = 'hello123456';
var newStr = '';
// get index where unwanted text starts
var index = originalStr.indexOf('v=') + 2;
newStr = originalStr.substring(0, index); //take part just before the unnecessary text
newStr += textToReplaceWith; //add string you want
newStr += originalStr.substring(index + 11, originalStr.length) // take text part after unwanted text

Related

Delete all occurence of href tag and keep the textes inside

I have a long String containing a HTML document. I want to delete all the href Tags but keep the text. The following example:
Some text example 1</p> some example 2text
should become:
Some text example 1 </p> some example 2 text
The solution I found is to get all the textes, and then try to iterate again through the text and replace the tag number n with the text number n.
var a_string = 'Some text example 1</p> some example 2text',
el = document.createElement('p');
el.innerHTML = a_string;
var a = el.querySelectorAll('a');
var texts = [].slice.call(a).map(function(val){
return val.innerHTML;
});
alert(texts);
// TODO ieterate and replace occurence n with texts[n]
Is there a besser way to do this?
After first line write following code
a_string = a_string.replace(/(<a.*?>)/g,'').replace(/<\/a>/g,' ');
You can use the following Regex:
var regex = /(<\s*a([^>]+)>|<\/\s*a\s*>)/ig;
var str = 'Some text example 1</p> some example 2text';
str.replace(regex, ""); //Some text example 1</p> some example 2text
Try below regex:
var a_txt = a_string.replace(/<a[\s]+[^>]*?href[\s]?=[\s\"\']*(.*?)[\"\']*.*?>/g,"").replace(/<\/a>/g," ");
Your solution of query-selecting all a-tags isn't actually too bad. Instead of getting the text with map you could just iterate over the list and replace each element with its content. No need for regular expressions:
el.querySelectorAll('a').forEach(function( a_el ){
var text = document.createTextNode(a_el.innerText);
a_el.parentNode.replaceChild(text, a_el);
});
also, instead of "parsing" your html by putting it into a p-element, you could use a DomParser:
var parser = new DOMParser();
var doc = parser.parseFromString(a_string, "text/html");
doc.querySelectorAll('a').forEach(function( a_el ){
var text = document.createTextNode(a_el.innerText);
a_el.parentNode.replaceChild(text, a_el);
});
as stated in some answer above, your code isn't bad. I avoid the use of regular expression when not necessary.
To finish your code, you neeed to iterate through all A{ELEMENTS}. I am typing from mobile phone. Let me know if you hit an error. Thanks.
var a_string = 'Some text example 1</p> some example 2text',
el = document.createElement('p');
el.innerHTML = a_string;
var a = el.querySelectorAll('a');
for( var t = a.length - 1; t >=0 ; t-- ){
for(var c = a[t].childNodes.length - 1; c >= 0; c-- ){
if( a[t].nextSibling ){
document.insertBefore( a[t].childNodes[c], a[t].nextSibling );
} else {
a[t].parentNode.appendChild( a[t].childNodes[c]);
}
}
a[t].remove();
}

Javascript loop strings in between selected characters

I would like to know how to create a for-loop with text content that I cannot modify. The text I am given looks like so:
<start>John</stop><start>Billy</stop>
I have two texts, John and Billy that are each surrounded by start and stop tags. What I would like to do is add these names without the tags to my HTML. My incomplete code looks something like:
var mytext = "<start>John</stop><start>Billy</stop>";
var count = (mytext.match(/<start>/g) || []).length;
for (i = 0; i < count; i++){
something.innerHTML += eachname;
}
Would like to know how to complete this.
Try with /<[^>]*>/gi like the following:
Please Note: Since the output is plain text it is better to use textContent instead of innerHTML.
var mytext = "<start>John</stop><start>Billy</stop>";
function get_content() {
//var html = document.getElementById("txtInput").innerHTML;
document.getElementById("txt").textContent = mytext.replace(/<[^>]*>/gi, "");
}
get_content();
<div id="txt">
</div>
You can use the following javascript example for your solution.
var mytext = "<start>John</stop><start>Billy</stop>";
mytext = mytext.replace(/<\/?start[^>]*>/ig, ""); //Replace all <start> with blank
console.log(mytext.split(/<\/?stop[^>]*>/ig)); //Split by <stop> this may return an array ...

Replace script tag that has a dynamic version number which keeps changing

I would like to remove or replace this string in an HTML file using javascript.
'<script src="../assets/js/somejs.js?1.0.953"></script>'
Trouble is, the version number "1.0.953" keeps changing so I can't use a simple string.replace
You could achieve this using the following Regex:
\?.*?\"
Or, more specifically
(\d+)\.(\d+)\.(\d+)
For matching the version number.
Utilizing the regex, you can replace the version number with a blank value.
Ok this is messy but it works...
String.prototype.replaceAnyVersionOfScript = function(target, replacement) {
// 1. Build the string we need to replace (target + xxx + ></script>)
var targetLength = target.length;
var targetStartPos = this.indexOf(target);
var dynamicStartPos = targetStartPos + targetLength;
var dynamicEndPos = this.indexOf('></script>', dynamicStartPos) + 10;
var dynamicString = this.substring(dynamicStartPos, dynamicEndPos);
var dymamicStringToReplace = target + dynamicString;
// 2. Now we know what we are looking for. We can replace it.
return this.replace(dymamicStringToReplace, replacement);
};
shellHTML = shellHTML.replaceAnyVersionOfScript('<script src="./assets/js/CloudZoom.js', '');

Search through an entire string

How would you search through an entire string and display each item found in a div?
The thing I'm searching for is a license code which starts with NVOS and ends with ". I'd like to extract the entire code except for the "
The thing I want to parse would be like NVOS-ABCD-EFG-HIJK-LM52P" but I don't want the " included.
Here is what I'm trying:
var myRe = /^NVOS[^"]*/g;
var myArray = myRe.exec(document.getElementById("txt").value);
console.log(myArray)
for (i in myArray){
console.log(i)
}
Not working.
Use a regular expression.
var myString = document.body.innerHTML // substitute for your string
var regex = /NVOS[A-Z\-]+/g // /g (global) modifier searches for all matches
var matches = myString.match(regex);
for (var i=0; i<matches.length; i++)
console.log( matches[i] )
// NVOS-ABCD-EFG-HIJK-LM
// NVOS-ABCD-EFG-HIJK-LM
lests say that your string is str.
//check if the code even have this characters /x22 is for = " //
var newString = str.substr(str.indexOf("NVOS"),str.lastIndexOf("\x22") -1);
If you want to display each section in the console, then you could do it like this:
var licenseString = "NVOS-ABCD-EFG-HIJK-LM52P";
var stringSplit = licenseString.split("-");
for(var part in stringSplit) {
console.log(stringSplit[part]);
}

javascript/jquery shortening a string without cutting word off

say i had the string text = "this is a long string i cant display" i want to trim it down to 10 characters but if it doesnt end with a space finish the word i don't want the string variable to look like this "this is a long string i cant dis" i want it to finish the word until a space occurs. I'm trying this which was suggested by other people but .replace doesn't seem to be working but .length does? I read somewhere that javascript functions don't work inside jquery functions but i still don't understand why .length works
$(document).ready(function(){
$('.article').each(function(index){
var text = $(this).children('p').text()
var maxLength = 6;
var url = $(this).find('.article-link').attr('href');
alert(text.replace(/^(.{1}[^\s]*).*/, "$1"));
var trimmedString = text.substr(0, maxLength);
var text = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")));
//var text = text.substring(0, 80);
//text = text.replace(/^(.{10}[^\s]*).*/, "$1");
});
});
Seo duit, a chara:
var str = "The rain in Spain falls mainly on the plain.";
var l = 10;
while (str.length > l && str.substr(l-1,1) != " ") l++;
alert(str.substr(0,l));
Javascript functions most definitely do work inside jQuery functions. It looks like your regex might be the issue, if the replace function isn't working for you.
This code works:
$(document).ready(function() {
$('.article').each(function(index) {
var text = $(this).children('p').text();
var maxLength = 6;
var reg = new RegExp('^(.{' + maxLength + '}[^\\s]*).*');
alert(text.replace(reg, "$1"));
});
});
Here's a working example

Categories

Resources