Javascript replace a string - javascript

I want to change this
[s=http://stackoverflow.com/questions/ask?title=Javascript%20replace%20a%20string]Text[/s]
into this
Text
using javascript
I have try this one.
<script>
var str = "[s=/site_menu.xhtml?get-d=4%2027&get-id=315&get-title=DanMachi%20Season%202&get-main=DanMachi]DanMachi Season 2[/s]";
var res = str.replace("[s=", '<a href="');
var ser = res.replace("[/s]", "</a>");
var serr = ser.replace("]", ':admin-hash-amp:">');
document.write(serr);
</script>

You may want to consider simply creating a function that would encapsulate all of this for you, especially if you plan on using in within multiple areas of your application:
function toHyperLink(input){
return input.replace('[s=','<a href="')
.replace(']','">')
.replace('[/s]','</a>');
}
Example
var input = '[s=http://stackoverflow.com/questions/ask?title=Javascript%20replace%20a%20string]Text[/s]';
console.log(`Input: ${input}`);
console.log(`Output: ${convertToHyperlink(input)}`);
function convertToHyperlink(input) {
return input.replace('[s=', '').replace('[/s]', '');
}

After you do your convert you should create an element instead of write that out.
var str = "[s=http://stackoverflow.com/questions/ask?title=Javascript%20replace%20a%20string]Text[/s]";
var res = str.replace("[s=", '<a href="');
var ser = res.replace("[/s]", "</a>");
var serr = ser.replace("]", '">');
var text = serr.slice(serr.indexOf(">") + 4, serr.indexOf("</a&gt"))
var href = serr.slice(serr.indexOf("href=\"") + 6, serr.indexOf("\"&gt"))
var link = document.createElement("a");
link.text = text;
link.href = href;
document.getElementById("myDIV").appendChild(link);

Try this
var str = "[s=http://stackoverflow.com/questions/ask?title=Javascript%20replace%20a%20string]Text[/s]";
var r = str.replace(/\[s=(.*?)\](.*?)(\[\/s\])/gi,"<a href='$1'>$2</a>");
document.write(r);

I guess you may also do like;
var str = "[s=http://stackoverflow.com/questions/ask?title=Javascript%20replace%20a%20string]Text[/s]",
res = str.replace(/\[s(.+)\](.+)\[\/s\]/, "<a href$1>$2</a>");
console.log(res);

Related

Remove HTML tags in script

I've found this piece of code on the internet. It takes a sentence and makes every single word into link with this word. But it has weak side: if a sentence has HTML in it, this script doesn't remove it.
For example: it replaces '<b>asserted</b>' with 'http://www.merriam-webster.com/dictionary/<b>asserted</b>'
Could you please tell me what to change in this code for it to change '<b>asserted</b>' to 'http://www.merriam-webster.com/dictionary/asserted'.
var content = document.getElementById("sentence").innerHTML;
var punctuationless = content.replace(/[.,\/#!$%\؟^?&\*;:{}=\-_`~()”“"]/g, "");
var mixedCase = punctuationless.replace(/\s{2,}/g);
var finalString = mixedCase.toLowerCase();
var words = (finalString).split(" ");
var punctuatedWords = (content).split(" ");
var processed = "";
for (i = 0; i < words.length; i++) {
processed += "<a href = \"http://www.merriam-webster.com/dictionary/" + words[i] + "\">";
processed += punctuatedWords[i];
processed += "</a> ";
}
document.getElementById("sentence").innerHTML = processed;
This regex /<{1}[^<>]{1,}>{1}/g should replace any text in a string that is between two of these <> and the brackets themselves with a white space. This
var str = "<hi>How are you<hi><table><tr>I<tr><table>love cake<g>"
str = str.replace(/<{1}[^<>]{1,}>{1}/g," ")
document.writeln(str);
will give back " How are you I love cake".
If you paste this
var stripHTML = str.mixedCase(/<{1}[^<>]{1,}>{1}/g,"")
just below this
var mixedCase = punctuationless.replace(/\s{2,}/g);
and replace mixedCase with stripHTML in the line after, it will probably work
function stripAllHtml(str) {
if (!str || !str.length) return ''
str = str.replace(/<script.*?>.*?<\/script>/igm, '')
let tmp = document.createElement("DIV");
tmp.innerHTML = str;
return tmp.textContent || tmp.innerText || "";
}
stripAllHtml('<a>test</a>')
This function will strip all the HTML and return only text.
Hopefully, this will work for you
if you need to remove HTML tags And HTML Entities You can use
const text = '<p>test content </p><p><strong>test bold</strong> </p>'
text.replace(/<[^>]*(>|$)| |‌|»|«|>/g, '');
the result will be "test content test bold"

Not Working .innerHTML

I am a seller on eBay and I want to use JavaScript on eBay. I have successfully used document.write to put the source file of JavaScript. The problem is it not working
This is my JavaScript:
window.onload = function trackt(){
if (typeof this.href === "undefined") {var str = document.location.toString();}
else {str = this.href.toString();}
var pos = str.indexOf("itm/");
var newStr = str.substring(pos+4);
var pos1 = newStr.indexOf("-/");
var newStr1 = newStr.substring(0,pos1);
var newStr2 = newStr1.replace(/\-/g,' ')
document.getElementById("cssmenu1").innerHTML = newStr1;
}
This my css:
#cssmenu_box{}#cssmenu1{float:left;right:-2%;padding:9;width:940px;height:31px;font-size:25px;background:transparent url('http://www.endition.net/ebay/templates/001/images/menu_bg.jpg') repeat-x top left;font-family:'Trebuchet MS',Helvetica,Arial,Verdana,sans-serif;color:#FFFFFF;border: 0.5px solid;border-radius:10px;}
This is my html code:
<div id="cssmenu_right"></div><div id="cssmenu1">Men Leather Jacket</div>
.innerHTML is showing error when I run it using console. I have to use document.write() function.
window.onload = function trackt(){
if (typeof this.href === "undefined") {var str = document.location.toString();}
else {str = this.href.toString();}
var pos = str.indexOf("itm/");
var newStr = str.substring(pos+4);
var pos1 = newStr.indexOf("-/");
var newStr1 = newStr.substring(0,pos1);
var newStr2 = newStr1.replace(/\-/g,' ')
document.getElementById("cssmenu1").innerHTML = newStr1;
}
//instead of innerHTML use text(newStr1);

Javascript make dynamic links but ignore existing links

Im using this to dynamically make links in a webpage:
var linkWord = function(obj){
for(i in obj){
var x = document.body.innerHTML;
var linkStart = '<a href="'+obj[i]+'">';
var linkEnd = '</a>';
var reg = new RegExp("\\b(" + i + ")\\b","ig");
x = x.replace(reg, linkStart + i + linkEnd);
document.body.innerHTML = x;
}
console.log(obj);
}
linkWord({
'The':'http://www.example.com',
'Vokalia':'http://icant.co.uk',
'Brent':'http://google.com',
});
This creates links in the page that matches the keyword, but overwrites existing hrefs if it also matches. How can I improve this to ignore the existing links?
No jQuery please.
https://jsfiddle.net/o43Lxmtr/
You can fix it by appending negated sets to the reg expression in order to discard words that are prefixed by > and suffixed by <.
Edit: A better approach might be to build a negative lookahead in order to disallow text contained inside tags.
Edit again: it is even better if the negative lookahead only works for anchor tags:
var linkWord = function(obj){
for(i in obj){
var x = document.body.innerHTML;
var linkStart = '<a href="'+obj[i]+'">';
var linkEnd = '</a>';
var reg = new RegExp("\\b(" + i + ")\\b(?![^<]*>|[^<>]*<\/[a])","ig");
x = x.replace(reg, " " + linkStart + i + linkEnd + " ");
document.body.innerHTML = x;
console.log(document.body.innerHTML);
}
console.log(obj);
}
linkWord({
'The':'http://www.example.com',
'Vokalia':'http://icant.co.uk',
'behind':'http://google.com',
});
Note that spaces were also added before and after the replaced string since the regex would strip them.
Edit: working demo here.
Edit2: working demo for second solution here.
Edit3: working demo for third solution here.
It looks like this question was answered before I could come up with a solution, and its also much cleaner than my solution. Good Job
It would seem, after testing your code under various circumstances,
that the best way to accomplish this is to remove your links from
the layout before running your function, and add them again once it is
completed.
Keep in mind we are only removing the inner contents of those
tags, so it will be necessary to store these in order so that they will be added again in the correct places.
JAVASCRIPT
var links_array = {};
var links = document.getElementsByTagName('a');
var linkWord = function(obj){
for(i in obj){
var x = document.body.innerHTML;
var linkStart = '<a class=added href="'+obj[i]+'">';
var linkEnd = '</a>';
var reg = new RegExp("\\b(" + i + ")\\b","ig");
x = x.replace(reg, linkStart + i + linkEnd);
document.body.innerHTML = x;
}
}
function getPrevLinks(){
for(link in links){
if(typeof links[link] === 'object'){
if(! links[link].hasAttribute('class')){
links_array[links[link].innerHTML] = links[link].href;
links[link].innerHTML = '';
}
}
}
return links_array;
}
function returnLinks(links, links_array){
console.log(links);
console.log(links_array);
for(link in links){
if (links[link].innerHTML === ""){
for(prop in links_array){
if(links[link].innerHTML === ""){
links[link].innerHTML = prop;
delete links_array[prop];
}
}
}
}
}
getPrevLinks();
linkWord({
'The':'http://www.example.com',
'Vokalia':'http://icant.co.uk',
'Brent':'http://google.com',
});
returnLinks(links, links_array);
HTML
<body>
<p id=me>The Vokalia Brent some more stuff and
The Vokalia Brent 1
The Vokalia Brent 2
The Vokalia Brent 3
<p>some paragraph</p></p>
<script src="java.js"></script>
</body>
If you need a detailed explanation just leave me a comment.
And the fiddle

Javascript Regex first character after occurence

I have a pager with this url: news?page=1&f[0]=domain_access%3A3".
I need a regex to replace the page=1 with page=2
The 1 and 2 are variable, so I need to find page= + the first character after that.
How can I do that
#EDIT:
from the answers, I distilled
var url = $('ul.pager .pager-next a').attr("href");
var re = /page=(\d+)/i;
var page = url.match(re);
var splitPage = page[0].split("=");
var pageNumber = parseInt(splitPage[1]);
pageNumber += 1;
var nextPagePart = 'page=' + pageNumber;
var nextPageUrl = url.replace(re, nextPagePart);
$('ul.pager .pager-next a').attr("href", nextPageUrl);
There might be a shorter approach ?
Like this:
var url = 'news?page=1&f[0]=domain_access%3A3"';
var page = 2;
url = url.replace(/page=\d+/, 'page=' + page);
EDIT
To achieve what did in your edit:
var obj = $('ul.pager .pager-next a');
var url = obj.attr('href');
url = url.replace(/page=\d+/, 'page=' + (++url.match(/page=(\d+)/)[1]));
obj.attr('href', url);
If you want to replace only a page number and leave the rest You can try something like this:
s/\(.*\)page=\d{1,}\(.*\)/\1number_to_replace\2/

appending values to textbox using for loop javascript

I am trying to add values to a textbox when looping through an array when checking checkboxes but as it is at the moment getting undefined.
Advice perhaps as to why the values are 'undefined'
var txtBoxValues = [];
$(document).on("click", "input[name=chkRelatedTopics]", function () {
var nameAdminUser = $(this).val();
var txtBox = document.getElementById("txtTraningTopics");
txtBox.value = '';
txtBoxValues.push(nameAdminUser);
for (var i in txtBoxValues) {
var str = txtBoxValues[i].value;
txtBox.value += str + '; ';
}
});
nameAdminUser is already a string, so don't take .value from it.
You could replace
var str = txtBoxValues[i].value;
with
var str = txtBoxValues[i];
But instead of using this loop, and assuming you don't want, as I suppose, the last ";", you could also do
txtBox.value = txtBoxValues.join(';');
nameAdminUser seems to be a String and in your for loop you expect an object. What if you simply do:
for (var i in txtBoxValues) {
var str = txtBoxValues[i];
txtBox.value += str + '; ';
}

Categories

Resources