Replace text in html string - javascript

I'm trying to write a regular expression for following criteria
The source string might optionally contain an html code. Which should be preserved, everything outside tag should replace with a static text.
function replaceCode( mystring ){
var replaceWith = "Hello!!!" ;
//do something with mystring here..
}
var string1 = "<span>Title</span> A small note" ;
var string2 = "Another big note" ;
alert( replaceCode(string1) ) ;
alert( replaceCode(string2) ) ;
Resultant strings must be
//string1 must become
<span>Title</span> Hello!!!
//string2 must become
Hello!!!

You may do following:
var yourString = "<span>Title</span> any text to replace";
var yourReplacement = "Hello!";
//Split by html tags
var tokens = yourString.split(/<\w+>\w+<\/\w+>/);
for (var i = 0; i < tokens.lenght; i++) {
yourString = yourString.replace(tokens[i], yourReplacement);
}
This, however, is probably not the best solution and will not work for nested tags but fit your examples.

Related

Escape a double quote within a match via Regex

I have a String that holds a number of double quotes and I would like to replace only those which are between certain characters.
Example String:
"XML": "<MyTag>"Value1"</MyTag><MyTag2>Value2</MyTag2>"
I would like the output to be:
"XML": "<MyTag>\"Value1\"</MyTag><MyTag2>Value2</MyTag2>"
I have tried variations of the below in regexr to attempt to match the quotes, but I am unsuccessful:
/<MyTag>(")<\/MyTag>/
/(<MyTag>)"(<\/MyTag>)/
Is it possible to add an escape to the quotes between my tags?
If it's very specific just like you write a simple replace() would be much simpler and demand less resources:
var str = '"XML": "<MyTag>"Value1"</MyTag><MyTag2>Value2</MyTag2>"';
// replace
str = str.replace('<MyTag>"','<MyTag>\\"');
str = str.replace('"</MyTag>', '\\"<MyTag>');
// test
alert(str);
JSFiddle:
https://jsfiddle.net/xbe1x0mz/
var sampleString = '"<MyTag>"value1"</MyTag><MyTag>value2</MyTag>"';
var first = sampleString.replace(/<MyTag>"/g, "<MyTag>\\\"")
var second = sampleString.replace(/"</MyTag>/g, "\\\"<MyTag>")
// second = "<MyTag>\"value1\"</MyTag><MyTag>value2</MyTag>"
Do not manipulate XML data with a regular expression! Especially when doing the thing correctly is so easy:
// Convert XML string to DOM:
var root = new DOMParser().parseFromString(YOUR_XML_DATA, 'text/xml');
// Manipulate all elements you want to:
var all_my_tags = root.querySelectorAll('MyTag');
for (var i = 0, len = all_my_tags.length; i < len; ++i) {
var my_tag = all_my_tags[i];
my_tag.textContent = my_tag.textContent.replace(...);
}
// Convert DOM to an XML string again:
var xml_data = new XMLSerializer().serializeToString(root);
Cf.
https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
https://developer.mozilla.org/en-US/docs/Web/API/XMLSerializer

How to capitalize first letter of every single word in a text area?

i have a multiline textfield("Adressfeld"), and i want to Uppercase every first letter and LowerCase the rest of every single word in this text area.
Here is my try:
function capitalize(Eingabe){
Eingabe = this.getField("Adressfeld").value;
var strArr = Eingabe.split(" ");
var newArr = [];
for(var i = 0 ; i < strArr.length ; i++ ){
var FirstLetter = strArr[i].charAt(0).toUpperCase();
var restOfWord = strArr[i].slice(1).toLowerCAse();
newArr[i] = FirstLetter + restOfWord;
}
return newArr.join(' ');
}
Ausgabe = this.getField("Empfängername");
Ausgabe.value = capitalize();
With the script shown above, every single word in the first line of the text area is capitalized. But in every other line, the first word isn't capitalized.
How i have to change the script to get it work?
Thanks,
I have included an example below try like that, it will solve your problem
Html
<input type="button" value="clk" onclick="z();"/>
<textarea rows="4" id="text" cols="50">
JS
function z()
{
var z=document.getElementById("text").value;
var x=z.replace(/\b./g, function(m){ return m.toUpperCase(); });
alert(x);
}
DEMO
I you want to Convert Every first letter of each word to upper and all other letters are lower then first convert the entire string to lowercase.Then do the same things as above.
DEMO2
Meinst du sowas?
var textToArray = document.getElementById('myTextarea').value.split('\n');
/* Hier eine Schleife zur Bearbeitung von textToArray */
var arrayToString = textToArray.join(' ');
The split operation fails -- the result of the first split cannot be split again on another character.
I see no reason to first replace returns by a single type \n and then try to split on either \n or a space. It's way easier to just replace the returns by a single space and only then split:
var strArr = String(Eingabe.value).replace(/[\r\n]+/g," ").split(" ");
With that, the rest seems to work.
Here is another approach, which may or may not work as well (it depends on whether Javascript's interpretation of "word boundary" \b agrees with your own):
function capitalize(Eingabe){
// Eingabe = this.getField("Adressfeld");
var strArr = String(Eingabe.value).replace(/[\r\n ]+/g,' ');
strArr = strArr.replace (/\b[a-z]/g, function(found) { return found.toUpperCase(); });
return strArr;
}
A few things:
• The argument of the function is Eingabe. In this case, this is a variable containing a value, and it does not make sense at all to redefine in the first line of the function. The way the function looks like, you won't need an argument, and therefore, your function definition looks like this:
function capitalize() {
• That done, define Eingabe properly as var Eingabe .
• With the array, you essentially want to create a two-dimensional array. First create the array of lines and then a loop through the lines, as it has been suggested in the answer by #Entimon
• You end with
this.getField("Adressfeld").value = capitalize() ;
And that should do it.
thanks for your help!
The correct answer is based on Arunprasanth KV's jsfiddle.net/svh1jd99
function capitalize()
{
var capitalize = this.getField("Adressfeld").value;
var done = capitalize.replace(/\b./g, function(m){ return m.toUpperCase();});
return done;
};
this.getField("Adressfeld").value = capitalize();
Thanks again for your help.
By using jQuery you can do this as shown below:
Demo: https://jsfiddle.net/cxow8198/3/
<input type="text" id="input">
<script>
//usage
$("input").keyup(function() {
toUpper(this);
});
//function
function toUpper(obj) {
var mystring = obj.value;
var sp = mystring.split(' ');
var wl=0;
var f ,r;
var word = new Array();
for (i = 0 ; i < sp.length ; i ++ ) {
f = sp[i].substring(0,1).toUpperCase();
r = sp[i].substring(1).toLowerCase();
word[i] = f+r;
}
newstring = word.join(' ');
obj.value = newstring;
return true;
}
</script>
Query code snippet to make capitals of the first letter of every word in the string. This could be used to prevent users from entering all caps for titles or text when they input data into forms.

Overflowed text with html in another div

I want to have a text that overflows in another div, so I found and used this answer from another question at Stackoverflow.
The problem is that only plain text is displayed; links, bold/italics and paragraphs are ignored.
Here is the same jsfiddle from the answer, but with added html tags. How do i get to display them?
Code:
var currentCol = $('.col:first');
var text = currentCol.text();
currentCol.text('');
var wordArray=text.split(' ');
$.fn.hasOverflow = function() {
var div= document.getElementById( $(this).attr('id') );
return div.scrollHeight>div.clientHeight;
};
for ( var x = 0; x < wordArray.length; x++ ) {
var word = wordArray[x];
currentCol.append(word+' ');
if ( currentCol.hasOverflow() ) {
currentCol = currentCol.next('.col');
}
}
Any tips or advice will be appreciated :)
jQuery .text method returns only plain text. Try using .html instead.
Example:
var text = currentCol.html();
But if your tags contain any spaces (like <span class="some-class">) then the following line from your code will do a mess with your text
var wordArray=text.split(' ');
You might want to change it to
text = text.replace(/ (?![^<>]*>)/gi, '%^%');
var wordArray = text.split('%^%');
This is kind of workaround since you could iterate over each regex match and substring it on every space character but IMHO the above idea with %^% combination is much more simple. you can replace those 3 signs with anything you want. I just thought it is unique enough that won't be used in any other purpose.
Above regular expression is simplified and assumes that you don't use < and > signs in your text.
If you actually do I would recommend to replace them with < and > anyway.

Add line breaks after n numbers of letters in long words

A have a string that can reach up to 100 characters in lenght. Is there an easy way to insert line breaks in the word every 10th letter? For example:
aaaaaaaaaaaaaaaaaaaaaaaaa
Should turn in to
aaaaaaaaaa<br/>aaaaaaaaaa<br/>aaaaa
I know that i can modify html with the html() method, but im not sure how to count characters and insert the tags. Thanks
Here is one option:
string.match(/.{1,10}/g).join("<br/>");
Assuming the text is inside a div or a span:
<div id="myDiv">aaaaaaaaaaaaaaaaaaaaaaaaa</div>
You can do:
$(function() {
var html=$('#myDiv').html();
var newHtml='';
for (var i=0;i<html.length;i++) {
newHtml=newHtml+html[i];
if ((i+1)%10==0) {newHtml=newHtml+'<br/>';}
}
$('#myDiv').html(newHtml);
});
Here is example: http://jsfiddle.net/68PvB/
Good Luck!
If you have your string in a variable you can use its replace method like this:
var chunklen = 2; //the length of the chunks you require
var str = '123456789'; //your string
var rxp = new RegExp( '(.{'+chunklen+'})', 'g' );
var str2 = str.replace( rxp, '$1<br/>' );
console.log( str2 ); //12<br/>34<br/>56<br/>78<br/>9

javascript - replacing text not between in attributes

I'm trying to replace text inside an HTML string with Javascript.
The tricky part is that I need to replace the text only if it isn't inside a tag (meaning it's not part of an attribute):
var html_str = '<div>hi blah blah<img src="img.jpg" alt="say hi" />hi!</div>';
In this example, after I do html_str.replace("hi","hello"); I want to replace only the text inside the div and a tags, avoiding the <img alt=".." or the href="....
Some more info:
html_str = document.body.innerHTML;, therefore the elements are unknown. The example above is only an example.
Regex are more than welcome.
The hi and hello values are inside varaibles, meaning the actual replace is like so: html_str.replace(var1,var2);
The REAL code is this:
var html_str = document.body.innerHTML;
var replaced_txt = "hi";
var replace_with = "hello";
var replaced_html = html_str.replace(replaced_txt,replace_with);
I hope I explained myself well.
Thanks in advance.
This maybe?
var obj = {'hi':'hello','o':'*','e':'3','ht':'HT','javascrpit':'js','ask':'ASK','welcome':'what\'s up'}; // This may contain a lot more data
(function helper(parent, replacements) {
[].slice.call(parent.childNodes, 0).forEach(function (child) {
if (child.nodeType == Node.TEXT_NODE) {
for (var from in replacements) {
child.nodeValue = child.nodeValue.replace(from, replacements[from]);
}
}
else {
helper(child, replacements);
}
});
}(document.body, obj));
http://jsfiddle.net/G8fYq/4/ (uses document.body directly)
If you want to make the changes visible immediately then you could also pass document.body and forget about the whole container stuff.
Update to allow for multiple replacements in one run.
You could also try XPath in javascript, though the following solution will not work in IE.
var
replacements = {'hi':'hello','o':'*','e':'3','ht':'HT','javascrpit':'js','ask':'ASK','welcome':'what\'s up'},
elements = document.evaluate('//text()', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null),
i = 0,
textNode, from;
for (; i < elements.snapshotLength; i += 1) {
textNode = elements.snapshotItem(i);
for (from in replacements) {
if (replacements.hasOwnProperty(from)) {
textNode.nodeValue = textNode.nodeValue.replace(from, replacements[from]);
}
}
}
Actually it is possible to use this simple regex negative lookahead:
(?![^<>]*>)
Just add it to your match pattern and it will exclude any content as attributes in tags. Here is an example:
Javascript regex: Find all URLs outside <a> tags - Nested Tags
You can try this, but regexp and HTML are not friends:
var str = '<div>hi blah blah<img src="img.jpg" alt="say hi" />hi!</div>',
rx = new RegExp('(\>[^\>]*)' + 'hi' + '([^\>=]*\<)', 'g');
str = str.replace(rx, '$1hello$2');

Categories