This is a code, ive used to maximize 5 words in each title
<script>
jQuery(document).ready(function() {
var limitWord = jQuery(".description").html();
limitWord.val(limitWord.val().substr(0, 5));
});
</script>
You can use the split function,
I have created a simple jsFiddle however it can be improvemed :)
jsFiddle : https://jsfiddle.net/nbj8ch45/
html
<div class="title">
this is a title with many different words
</div>
jquery
$(function()
{
var text = $('.title').text();
var words = text.split(' ');
$('.title').text(words[0]+' '+words[1]+' '+words[2]+' '+words[3]+' '+words[4]);
});
Here you are your example working
http://jsfiddle.net/2ad3cb3p/5/
var limit = 5;
$(document).ready(function() {
var descs = $(".description");
descs.each(function() {
var txt = $(this).html().split(" ");
var newTxt = '';
for(var i = 0; i < limit ; i++) {
newTxt += txt[i] + " ";
}
$(this).html(newTxt);
});
});
this might help you
jQuery(document).ready(function() {
var limitWord = jQuery(".description").html();
limitedWord = getWords(limitedWord);
});
function getWords(str) {
return str.split(/\s+/).slice(1,6).join(" ");
}
You must use split() function
<script>
jQuery(document).ready(function() {
var limitWord = jQuery(".description").html();
var res = str.split(" ");
});
</script>
In res[0] to res [4], you have the 5 words, see in:
http://www.w3schools.com/jsref/jsref_split.asp
<script>
jQuery(document).ready(function() {
var limitWord = jQuery(".description").html();
limitWord.val(limitWord.val().split(' ').slice(0, 5).join(' '));
});
you can try this
this should work:
<script>
jQuery(document).ready(function() {
var limitWord = jQuery(".description").html();
var arr = limitWord.split(' ')
var str = "";
for(var i=0; i<arr.length && i<5; i++){
str += arr[i] + " ";
}
jQuery(".description").html(str)
});
</script>
heres a fiddle: http://jsfiddle.net/shLyLc0k/
Related
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>"))
var href = serr.slice(serr.indexOf("href=\"") + 6, serr.indexOf("\">"))
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);
I have an array with some elements in it.
var arr=["bet-vet","ban-van","baskat-vase"];
While displaying the array, the want the hyphen in between the words to be removed. When it is being displayed,
the user should see
Bet,vet,ban,van,baskat,vase
Here is the link of my code
You ca try:
var arr = ["bet-vet", "ban-van", "baskat-vase"];
arr= arr.join("-").split("-").join();
console.log(arr);
Use Javascript Joint() & Split() method
example:
var arr=["bet-vet","ban-van","baskat-vase"];
var arrJoin = arr.join("-");
var arrsplit = arrJoin.split("-");
console.log(arrsplit);
You can try this
<script>
var b_or_v =["bet-vet","bat-vat","reb-rev","bick-vic","ban-van"];
function removeHyphen()
{
var newArray = [];
for(i=0;i<b_or_v.length;i++)
{
res = b_or_v[i].split("-");
newArray.push(res[0]);
newArray.push(res[1]);
}
console.log(newArray);
document.getElementById("text").innerHTML = newArray;
}
</script>
<body>
<button onclick="removeHyphen()">Find Val</button>
<div id="text">
</div>
</body>
Here is jsFiddle link
Try to use code as mentioned below:
document.getElementById("btn-1").onclick= function(){
document.getElementById("submit").onclick= function(){
var txt = [];
for (var i = 0; i < b_or_v.length; i++) {
if(b_or_v[i].match(/-/g)){
txt += b_or_v[i].split('-');
txt += ', ';
}
else{
txt += b_or_v[i]+', ';
}
}
Output: b_or_v : bet, vet, bat, vat, reb, rev, bick, vic, ban, van,
What about something like this:
var arr = ["bet-vet", "ban-van", "baskat-vase"];
var arr1 = [];
for(var i= 0; i < arr.length;i++){
test= arr[i].replace('-', '');
arr1.push(test);
}
console.log(arr1.join(', '));
I'm editing this to add my solution based on georg's answer. The solution is at the bottom.
I am trying to get the enclosed text from a given tag using.
var substring = txt.find(tag).eq(i).text();
Sample Data:
The variable tag holds "h1".
The variable txt holds "<p>one.</p><h1>fish</h1><p>two fish. red fish. blue fish.</p>".
The Expectation:
subString == "fish"
The Result:
subString == null
Code:
this.mpactIdeation_getTagContentsKeyphrase = function( tag, kp ) {
try {
var result = 0;
var num = 0;
var txt = this.oText;
var tagcount = this._mpactIdeation_countOccurrences( txt, tag, false );
txt = jQuery(txt);
for (i = 0; i < tagcount; i++) {
tag = this._mpactIdeation_tagToText(tag);
var substring = txt.find(tag).eq(i).text();
result += this._mpactIdeation_countOccurrences(substring, kp, false);
}
return result;
} catch(e) {
console.log(e);
return false;
}
}
Solution:
this.mpactIdeation_getTagContentsKeyphrase = function( tag, kp ) {
try {
var result = 0;
var num = 0;
var txt = this.oText;
var tagcount = this._mpactIdeation_countOccurrences( txt, tag, false );
for (i = 0; i < tagcount; i++) {
tag = this._mpactIdeation_tagToText(tag);
var substring = jQuery('<div>').html(txt).find(tag).eq(i).text();
result += this._mpactIdeation_countOccurrences(substring, kp, false);
}
return result;
} catch(e) {
console.log(e);
return false;
}
}
To use find you have to put your html in a container:
txt = "<p>one.</p><h1>fish</h1><p>two fish. red fish. blue fish.</p>";
result = $('<div>').html(txt).find('h1').text()
alert(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This is how I would do it:
var tag="h1"
var txt = "<p>one.</p><h1>fish</h1><p>two fish. red fish. blue fish.</p>";
var result = txt.match(new RegExp("<"+tag+">(.*)</"+tag+">"));
console.log(result[1]);
alert(result[1]);
Here is the JSFiddle demo
The string was filtered using the tag u provided via regex and the text between the tags are shown as a message.
I have tried doing in a similar fashion and was able to do it quite well.
Please refer demo.
Code below:
HTML:
<div class="test">Test div 1</div>
<div class="test">Test div 2</div>
<div class="test">Test div 3</div>
<div class="newDiv"><p>New Div</p></div>
JS:
$(function(){
var len = document.getElementsByClassName('test').length;
for(var i = 0; i<len;i++){
var test = $('.test').eq(i).text();
$('.newDiv').append('<br>Loop ' + (i+1) + ' text = ' + test);
}
});
If I have webpage with for example alot of <td class="house">111 22</td>. The numbers are random but classname is the same and the blankspace between the numbers are at same position in all of them, and I want to remove the space in all of them after page is loaded. How should the script look like to work?
How about using this
var str = "111 22";
str = str.replace(" ","");
code example :
<script type="text/javascript">
//Page Initial
$(function() {
removeSpace();
});
function removeSpace(){
var str = $(".house").html();
str = str.replace(" ","");
$(".house").html(str);
}
</script>
Do this:
var elems = document.querySelectorAll('td.house');
for(var i = 0 ; i < elems.length; i++){
elems[i].textContent = elems[i].textContent.replace(" ","");
}
use the following code:
<script type="text/javascript">
window.onload = removeSpace;
function removeSpace() {
var emt = document.getElementById("mytable");//mytable is the Id of the table
d = emt.getElementsByTagName("tr")[0],
r = d.getElementsByTagName("td");
for (var i = 0; i < r.length; i++) {
var str = r[i].innerText;
r[i].innerText = str.replace(" ", "");
}
}
</script>
I have this:
<div id="testcase">abcdefghijklmnopqrstuvwxyz</div>
I would like to add this: <span> with an offset.
So when I for example would have the JS function: addSpan(4) this would happen:<div id="testcase">abcd<span>efghijklmnopqrstuvwxyz</div>
To visualise what I'm looking for:
function addSpan(i){
$('#testcase').append('<span>', i);
}
Use slice and concatinate...
function addSpan(i){
var content = $("#testcase").html();
var before = content.slice(0, i);
var after = content.slice(i + 1);
$("#testcase").html(before + "<span></span>" + after);
}
Here another wut i tired LIVE DEMO
$("#btn_clck").on('click', function () {
var gText = $("#testcase").html();
var getlength = gText.length;
var finalValue = "";
for (var i = 0; i < getlength; i++) {
var setData = gText.charAt(i);
if (i == 4) {
finalValue += '<span></span>'
}
finalValue += setData;
}
$("#testcase").text(finalValue);
});
but i think Steini's answers was better