.split() a data attribute isn't working when it should - javascript

I want to .split(" ") a data attribute value but it returns empty:
var bulletcontent = jQuery(this).closest("div").find("p").attr('data-bcontent');
// split content into words
var words = jQuery(bulletcontent).text().split(" ");
Why isn't this working?
Here is a jsFiddle.

See the fiddle: https://jsfiddle.net/43439o8o/2/
You dont need to get the .text(), the .attr() already return his content:
var bulletcontent = jQuery(content).attr('data-bcontent');
// split content into words
var words = bulletcontent.split(" "); //Remove the .text() method
As you can see at the .attr() method docs, you can use it to return or set the attribute value:
Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

change this line:
var words = bulletcontent.split(" ");

$(document).ready(function() {
$(document).on("click", ".click", function() {
// find the bullet content stored in p tag inside li
var content = $(this).prev("p").attr('data-bcontent');//get the p attr
alert(content)
var words = content.split(' ')//split
alert(words[0]);//alert first value
alert(words[1]);//alert second value
});
});
DEMO

You can use directly function split() on the string:
var words = bulletcontent.split(" ");
for example you can see this link

.split() is a Method of String in Javascipt so there's no need to use jQuery. just add .split(' ') right next to your variable(String).
.split() returns array of strings depends on how you want to plit the original string.
This should work for you.
var words = bulletcontent.split(" ");

You can use this:
var words = bulletcontent.split(" ");

Related

Get HTML element attribute from javascript

I stuck again in beginner-spheres of JS. :/
I want to get the number from data-channel-id, which is found by the call in variable spans:
<main class="soft--top" data-channel-id="348" data-preview-mode="">
This is my JS:
window.onload = function (){
var spans = document.getElementsByTagName('main')[0];
var res = /[0-9]+/;
var match = res.exec(spans);
console.log(match);
}
I don't know how to proceed.
The Regex is correct, the document. variable "spans" shows the correct result, but matching won't show any output in the console.
What am I missing?
spans in your code currently contains the whole element.
To use only the data-channel-id value, see the code below:
var spans = document.getElementsByTagName('main')[0].getAttribute('data-channel-id');
spans is not string but HTMLElement, to get value of data-channel-id you can use getAttribute as mentioned in comment above or if you really want to use regex convert it to string with .outerHTML
window.onload = function() {
var spans = document.getElementsByTagName('main')[0];
var res = /[0-9]+/;
var match = res.exec(spans.outerHTML);
console.log(match);
}
I want to get the number from "data-channel-id"
No need to use regex. Just:
var spans = document.getElementsByTagName('main')[0];
var match = spans.getAttribute('data-channel-id');
console.log(match);
Working demo here.

Setting text within p tag with js variable

I am setting a text value within a p tag to a string being parsed out by splitting. When I alert the variable, I am able to see the text, however when I try to set the text to the variable value, I am unable to see a change. How do I edit this code to set the text within #view_head to the variables I pass within $('#view_head').text(//variable here//)?
The code
$(edit_but).click(function(e){ //on add input button click
//e.preventDefault();
//uses set input data to create variables for use in editor
var master_string = $('#string_text').text();
var key_string = master_string.split("|m|");
var name_string = key_string[0].split("|s|");
var cont_string = key_string[1].split("|s|");//contains contact variables
var adr_string = key_string[2].split("|s|");
var qual_string = key_string[3].split("|s|");//contains description and applying for blob text
var pos_key_string = key_string[4].split("|s|");
var edu_key_string = key_string[5].split("|s|");//key string to contain edu strings
var course_key_string = key_string[6].split("|s|");
var awd_key_string = key_string[7].split("|s|");
var skill_key_string = key_string[8].split("|s|");
var count_key_string ='';
var pos_string = pos_key_string[0].split("|j|");
alert (pos_key_string); //working
alert (name_string);
$('#view_head').text(key_string); //not working, does not change
alert (key_string); //working, can see value in alert for both
//window.location = '#openModal';
});
String.split() returns an array, and .text() waits for Type: String or Number or Boolean. - http://api.jquery.com/text/
Try to get it $('#view_head').text(key_string.toString()); or $('#view_head').text(key_string[0]); if data, that you are looking for is in first array element.
if text() is not working,maybe you could try val() or html()
Using String.split() returns an Array object, which you cannot insert into an HTML element as text. To create a String from an Array, which can be inserted into an HTML element, use the Array.join() method. EG.
var sample_string = "This is a String";
// split at spaces into an Array
var sample_array = sample_string.split(' ');
//--> ['This','is','a','String']
// join with spaces into a String
var another_string = sample_array.join(' ');
//--> "This is a String"
See MDN : String.prototype.split() & Array.prototype.join()

How to remove string from string until a specefic character using jquery

I want to remove the last parameter in the href of a specific tag using jquery
for example replace href="app/controller/action/05/04/2014"
by href="app/controller/action/05/04"
Try using the String.lastIndexOf() and String.substring() in this context to achieve what you want,
var xText ="app/controller/action/05/04/2014";
xText = xText.substring(0,xText.lastIndexOf('/'));
DEMO
if you know which value you need to change ,than you can use replace:
var str = "app/controller/action/05/04/2014";
var res = str.replace("2014","04");
or else you can use array and change / update last value in array:
var str = "app/controller/action/05/04/2014";
var res = str.split("/");
We can use a regular expression replace which will be the fastest, compared to substring/slice.
var hreftxt ="app/controller/action/05/04/2014";
hreftxt = hreftxt.replace(/\/[^\/]*$/,"");

Javascript need variable that can represent any number

I'm a javascript novice so this may be a dumb question. I'm trying to generate a script that takes the phrase "(x items)" and changes it to "(x)", where x can represent any number.
Here's what I have now:
<script type="text/javascript">
$(document).ready(function(){
function changeText(){
$(".CartLink:contains('2 items')").html('Cart <span>(2)</span>');
}
changeText();
$(document).ajaxSuccess(function() {
changeText();
});
});
</script>
The above script is able to replace the phrase "(2 items)" with "(2)" but I need to modify the script so that 2 can be any number. Thank you.
This is the HTML that .CartLink element contains:
<li style="display:" class="CartLink">Cart <span>%%GLOBAL_CartItems%%</span></li>
Ideally this should be a server-side task. But if you have a limitation requiring you to do this client-side...
You don't need to replace all of the html. You can simply modify the text of the span:
$('.CartLink span').text(function(_, val) {
return val.replace(' items', '');
});
Your can use split to seperate the count and text.
http://jsfiddle.net/B2meD/
$( document ).ready(function() {
$(".CartLink").html('Cart <span>'+$(".CartLink").text().split(" ")[0]+'</span>');
});
Javascript as a string replace method. So you can simply remove the items part.
var foo = ('2 items');
var newFoo = foo.replace("items", "");
Then newFoo would become ('2')
S('.CartLink').text($('.CartLink').text().split(' ')[0])
Where are you getting the "2" variable from?
var items = 2;
items ++; //items = 3;
$('.Cart').html("Items in cart:" + items.toString() + ". Foo");
See how I added the "+" to add up the strings?
I must add, this is just bad js.
For making your items variable:
var str = "(Items 2)";
var numberStr = "(" + str.split(" ").pop(); //makes "(2)" or use .replace or whatever works.
Keep in mind that making a variable from a string will result in another string. If you want to manipulate your new items var as a number, you have to get an integer like so,
var numberStr = "(3)";
var int = parseFloat(numberStr.replace(/["'()]/g,""));
If you replace your changeText function with this it should work as you want:
function changeText() {
var itemCountSpan = $(".CartLink a span")
if (/(\d+) items/.test(itemCountSpan.text())) {
itemCountSpan.text(RegExp.$1);
}
}
Here's a simple RegEx version.
$(document).ready(function(){
function changeText(){
$(".CartLink").each(function() {
var newhtml = $(this).html().replace(/\((\d+) items\)/, "($1)");
$(this).html(newhtml);
});
}
changeText();
});
It looks at every element with the CartLink class for the string (x items) where x is one or more digits and removes the word "items". $1 is a property that gets set when the (\d+) parenthesised match is made, allowing us to use the number we want in our replacement string.

group parts of a string into an array element

If I have a string... abcdefghi
and I want to use regex to load every elemnent into an array but I want to be able to stick anything connected by plus sign into the same element... how to do that?
var mystring = "abc+d+efghi"
output array ["a","b","cde","f","g","h","i"]
One way to do it:
var re = /([^+])(?:\+[^+])*/g;
var str = 'abcd+e+fghi';
var a = str.match(re).map(function (s) { return s.replace(/\+/g, ''); });
console.log(a);
The value of a[3] should now be 'def'.
http://jsfiddle.net/rbFwR/2
You can use this expression, to produce [a][b][c+d+e][f][g][h][i].
mystring.split ("(.\+)*.")
Next, replace any + characters with empty on the resulting list.
mystring.split("\\+")
Click here for more information.

Categories