how to replace a string in javascript after the specific index - javascript

Hi I am having the string which contains html content and I want use javascript to replace the tag <p class="MsoNormal"> with '' empty space and i want to replace corresponding closing tag </p> with <br> tag in that string.
If I use
first line:
str=str.replace(/<p class=\"MsoNormal\">/g,'');
second line: str=str.replace(/<\/p>/g,'<br>');
All the closing </p> tag get remove .But i want to replace the closing </p> tag which has the opening tag of "<p class="MsoNormal">".
The first line of script is okay of me .What should i use to replace that corresponding closing tag in the second line.

Check this: Output is what I got from your question is to replace with Empty String
var replaceTag = function(str, replaceTagString, endTagString) {
var str = '';
while(str.indexOf(replaceTagString) != -1) {
//search for </p> after my matched String
var indexOfClosingTag = str.indexOf(endTagString, str.indexOf(replaceTagString))
//Replace </p> using Substring
str = str.substr(0,indexOfClosingTag) + "<br>" + str.substr(indexOfClosingTag + endTagString.length,k.length)
//Replace your main String
str = str.replace(replaceTagString,'')
}
return str
}
var k = "<p class='MsoNormal'>something</p><p>other p tag</p><h1>I am h1</h1><p>Hello p</p><p class='MsoNormal'>Replace My Tag too</p>"
replaceTag(k, "<p class='MsoNormal'>", "</p>")
Output:
"something<p>other p tag</p><h1>I am h1</h1><p>Hello p</p>Replace My Tag too"
Concept:
string.indexOf(searchvalue,start)
Start searching for End of the Tag (P) after my current matched string position

Define a function yourself like this-->
String.prototype.replaceAt=function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
And use it like this:
str = str.replaceAt(3, "</p>");

Related

try to show html tags as text with innerHTML

I have a string that contains HTML tags.
I want to render as an HTML element only the span tags aka <span></span>.
every other tag that is not a span tag should be treated as regular text.
The result I'm trying to achieve is to color any text that I want even if it contains HTML tags.
I fail.
is there any other technique that I can try or a workaround?
var problem = ["<h1>","</h1>"];
var red_text = "<span style='color:red'>i am red </span>";
var green_text = "<span style='color:green'>" +
problem[0] +
"i am green" +
problem[1] +
"</span>";
//the real result should have <h1> </h1>
var expected_text = red_text + "<span style='color:green'>|h1|i am green|/h1|</span>";
document.getElementById("demo").innerHTML = red_text + green_text;
document.getElementById("expected").innerHTML = expected_text;
HTML and JavaScript code at :
https://jsfiddle.net/ytLftxww/1/
You need to use HTML entities to escape the < and > in those tags.
For example: "<span style='color:green'><h1>i am green</h1></span>"
See the fiddle: https://jsfiddle.net/ytLftxww/1/
var problem = ["<h1>","<h1>"];
does unescaping the < > work for you?
updated fiddle
You can use &lt for < and & &gt for >.

Href how to pass dynamic data

[![enter image description here][1]][1]In href how to pass path with dynamic data, below I'm giving my code:
var abc = response[i].DocumentName;
var photoName = "<a href='#Url.Content("~/UploadImage/")" + abc +'" target="_blank" >'+response[i].DocumentName+'</a>';
in debugger mode i am getting like this:-
photoName = "jpeg2_10514.jpg"
which is not working for me
Try this:
var photoName = "" + response[i].DocumentName + "";
In Javascript you have to escape doublequotes " with a backslash \ if you want them to appear in the string.
The backslash in + abc + "\" is there to escape the second " to enclose the href in doublequotes.
EDIT
I added the missing doublequote befor the anchor tag according to the tip of karan.

Javascript not able to replace text with new Text with html

I trying to replace text with new text inside a html tag like:
text = " hello how are you? " ;
newText = "<h1>hello how are you? </h1> " ;
This is my code:
//replacer holds the html element
var replacer = document.getElementById("#"+id);
var newElement = "<span style='font-size:100px;' id='one4'>"+selectedinnerText+"</span>";
//selectedinnerText holds the text to be replaced
alert(selectedinnerText + " "+ newElement );
//This below line is not working properly
replacer.innerHTML = replacer.innerHTML.replace(selectedinnerText,newElement);
Your issue is, when you are getting an element by its id in JavaScript, you do not need # infront of the id name.
var replacer = document.getElementById(id);
So, the reason why you cannot set the innerHTML of the replacer element is because there is no element stored in the variable right now.
The correct code should be
var replacer = document.getElementById(id);// no # needed here
var newElement = "<span style='font-size:100px;' id='one4'>"+selectedinnerText+"</span>";
alert(selectedinnerText + " "+ newElement );
replacer.innerHTML = replacer.innerHTML.replace(selectedinnerText,newElement);

How can I format text in an HTML <textarea>?

I have a <textarea> on my page, and when I click a button, the value of the text in the textarea is assigned to .innerHTML of a paragraph on my page.
Now let's say I type something like this in the textarea:
Hey
how's
it
going
?
The paragraph would look like this
Hey how's it going ?
Basically, it wouldn't have <br> tags at the end of each row. Is there a way I can force the JavaScript function to insert <br> tags at the end of each row of my textarea, or is there an easier way to do this?
JavaScript code:
document.getElementById("sendMsgBtn").onclick = function(){
var element = document.createElement("p");
element.style.borderBottom = "1px solid black";
var content = document.createTextNode(document.getElementById("currentMsg").value);
content = content.replace(/\n/g, "<br>");
element.appendChild(content);
document.body.appendChild(element);
document.getElementById("currentMsg").value = "";
}
You don't want line breaks. Trust me.
Just set this:
white-space: pre-wrap;
This CSS will make whitespace significant, preserving it as it was typed.
When you copy the element from the textarea to the paragraph tag, replace all line breaks with <br> tags:
var input = document.getElementById("myTextarea").innerHTML; // get textarea contents
input = input.replace( /\n/g, "<br>"); // replace line breaks with <br> tags
document.getElementById("myParagraph").innerHTML = input; // place html-ified input into your <p>
If you are using jQuery, try this:
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
Then nl2br(yourVariableWithContent); can be used to change newline characters (the ones that the return button makes) into <br/>.

How to get Surrounding word in javascript or jquery?

I am working with webview and loading the html pages in webview so here I got stuck somewhere, I want to use the javascript.here. I am explaing what I need exactly below:
I am having the html data like this-
"My selected the word "widget". But I'd like to know if the selection is after "red" or "blue". Is this possible? I've been scouring the Internet for some advice, and I'm having trouble finding an answer"
So suppose from above text I selected the text " selection is after"(which is shown bold) I need the previous words before this word and the words after this word in that line only. Suppose I select in line 2 so I need all the previous word in that line before the word and all words after the selected word in that line and in case if the selected word is in starting of line so return previous word as null and remaining word after the selected word up-to the end of line similarly for last word vice versa
Please tell we how to achieve it using JavaScript?
I created a solution in a JSFiddle at Selecting text before and after word
First I created a paragraph to hold the text to be selected
<p id="yourTextContainer">Lorem ipsum data sid amet</p>
Then, in the JavaScript, I split the paragraph into spans, placing the index of each word in the name attribute. Then, when a word is clicked it used the index to return all words before, and all words after.
var textindex;
var textbefore;
var textafter;
$(document).ready(function(){
var words=$("#yourTextContainer").text().split(' ');
$("#yourTextContainer").html("");
$.each(words, function(i,val){
//wrap each word in a span tag
$('<span name="'+ i+'"+ />').text(val +" ").appendTo("#yourTextContainer");
});
$("#yourTextContainer span").live("click",function(event){event.stopPropagation();
$("#yourTextContainer span").css("background-color","white");
$(this).css("background-color","blue");
//gets the text of clicked span tag
var textselected = $(this).text();
textindex = $(this).attr("name");
alert("You just selected "+textselected+" index " + textindex);
textbefore= "";
textafter = "";
$("span").each(function (index) {
// alert("LOOPING INDEX " + index);
if (index<(textindex))
textbefore = textbefore + $(this).text() + " ";
if (index>(textindex))
textafter = textafter + $(this).text() + " ";
});
alert("Text before is "+textbefore );
alert("Text after is "+textafter );
});
});
For example, if you click on "ipsum", the JS alerts, "Lorem" as the text before, and "data sid amet" as the text after "ipsum".
Hope this helps! You can also run the fiddle to see what I mean.
What about using match with a regular expression:
var pattern = /^(.+)(selection is after)(.+)$/;
match = "hello selection is after goodbye".match(pattern)
match[1] // hello
match[2] // selection is after
match[3] // goodbye

Categories