find text wrapped in brackets in jQuery - javascript

I have some text on a page and I want to located and remove any text found in brackets.
For example:
<td>here is [my text] that I want to look at</td>
So I want to grab that text (my text), save it in a variable and remove it from where it is.

If you're using jQuery you could use a regular expression like \[(.+)\] on $('body').text().
EDIT: Sorry, I might have jumped the gun a little bit giving you this answer. Going to think about it for a few more minutes and try to update this with a little more info.

You may find that this task is not all that simple. If you have control over the text before it is sent to the web browser you may want to put a <span class='bracket'>[my text]</span> around the text, then you could easily do something like this with jQuery:
$(".bracket").each(function() {
// store the data from $(this).text();
}).remove();
This can be done using regular expressions and jQuery, but there are problems that may creep up dealing with text inside of attributes like <input name='test[one][]' /> The "simple" regex would be to do something like this:
$("td").each(function() {
var $this = $(this);
var html = $this.html();
var bracketText = [];
// match all bracketed text in the html - replace with an empty string
// but push the text on to the array.
html = html.replace(/\[([^\]]+)\]/g, function() {
bracketText.push(arguments[1]);
return "";
});
// put the new html in away and save the data for later
$this.html(html).data("bracketText", bracketText);
});
There is not much danger in doing this if you're sure you wont have [] inside of tags other than in the text.

I ended up doing the following:
$('#formQuizAnswers td.question').each(function(){
var header = $(this).text().match(/-.*-/);
$(this).text($(this).text().replace(header,''));
});
I changed my text I search for to have dashes around it IE -My text-

Related

Regex for finding link

I have an issue related to finding a regex for the link with some conditions. Here is the scenario:
I have created utils.ts it's a typescript. basically, it will take an API response as an input and return the formatted HTML supported text, like bold text, email, Images, Links.
So let's take one scenario which I am facing.
as a return of the utils.ts file, I am getting this.
https://www.google.com Click here
(Note: normal links and 'a' tag links can occure in any order)
from the above text, as you can see this part Click here is already in HTML supported method.
So I will get the following output on GUI
https://www.google.com Click here
so from this point, I want a regex which can format https://www.google.com but it must not manipulate Click here as it is already formated.
Here I also want to format https:///www.google.com as follow
Google
The main problem I am facing is when I am replacing the string with 'https://..' with tags it will also replace the links inside 'href' like this
Google Google">Click me</a>
Which is what I don't want.
Please share your thought on this.
Thank you
Not yet formatted links can be found using alternations. The idea is - if a link is formatted it's not captured to a group (don't be confused that the regex still finds something - you should only look at Group 1). Otherwise, the link is captured to a group.
The regex below is really simple, just to explain the idea. You might want to update it with a better URL search pattern.
demo
(?:href="https?\S+")|(https?\S+)
If I understood correctly, you want to extract from the text those web addresses that appear in the text and are not links. If so check out the following javascript:
//the data:
var txt1='https://www.google.com Click here http://other.domain.com';
// strip html tags
String.prototype.stripHTML = function () {
var reTag = /<(?:.|\s)*?>/g;
return this.replace(reTag, " ");
};
var txt2=txt1.stripHTML();
//console.log(txt2);
//split tokens
var regex1 = /\s/;
var tokens = txt2.split(regex1);
//console.log(tokens);
//build an address table
regex2=/^https?:\/\/.*/;
var i=0, j=0;
var addresses=[];
for (i in tokens) {
if (regex2.test(tokens[i])) {
addresses[j] = tokens[i];
j++;
}
i++;
}
console.log(addresses);

JS. How do I replace text in the html () object within a variable?

Using JS I copied html code into variable.
html_block = $(".first-prj-container").html();
In some places it is necessary to make a replacement for the text. This can be either plain text or class names, IDs. Is it possible to make replacement via strReplace, and then append the result into the page like this:
$("#all-prj-container").append(html_block);
Try this:
let htmlToReplace = $(".first-prj-container").prop('outerHTML')
let updatedHtml = htmlToReplace.replace('hi', 'hello')
$("#all-prj-container").append(updatedHtml);
See more here outerHTML - MDN
you can also use regEx to refine your filter for white spaces, case sensitivity, or filter for certain nested tags:
let updatedHtml= $(".first-prj-container")
.innerHTML.toLowerCase() //make case-insensitive, can also be done with regEx "i"
.replace(/\s/g,'') //remove white spaces
.replace("(hi)(?!(.(?!<h1))*?</h1>)", "hello"); //skip h1 tag content
$(".first-prj-container").innerHTML = updatedHtml;

How to get text from tags, trimm, and paste to tags again in javascript

I would like to trimm text from html tags, and paste result to these tags again. It's not DOM content, only string.
var string = "<div class='someClass'><b>Some very long text</b></div>"
Wanted result is f.e.:
var string = "<div class='someClass'><b>Some very lon</b></div>"
I found library striptags, but it only gets rid off tags, but I want to keep them.
If you have any solution please let me know :)
UPDATE:
Thanks all of you for advices. There are few things to add from me: 1. I never have information about html tags, because it came from quill text editor, and I need some kind of regex. 2. In my job there is no jQuery, it's kind of 'evil' :P. 3. I'm using react, so any use of 'document' or 'window' is unwanted here :(.
Checkout trim() method of javascript or String.prototype.trim().
Hope it will work for you!
If it is a string and you want to trim some portion of text. you can use the substring/slice function of javascript.
For more refernce you can refer below links
http://www.w3schools.com/jsref/jsref_substring.asp
http://www.w3schools.com/jsref/jsref_slice_string.asp
You could use a hidden tag where you manipulate the string. Something like
<div id="tags-modifier" ></div>
and then jquery like like
var string = "<div class='someClass'><b>Some very long text</b><b>Test2213213213213</b></div>"
$("#tags-modifier").html(string);
var part= 5;
$.each($('#tags-modifier *:not(:has("*"))'), function(){
mytext=$(this).html()
$(this).html(mytext.substring(0, part))
})
string = $("#tags-modifier").html();
This works even if there are multiple siblings
Fiddle here
If the structure is exact like you showed <div class='someClass'><b>Some very long text</b></div>, you could do it with regex to find the text, and in the function change it how you like, shorten(substr)/trim/...:
var longText ="<div class='someClass'><b>Some very long text</b></div>";
const MAX_LENGTH = 13;
// regex expression matches the structure given
var shortText = longText.replace(/(<div[^>]+><b>)([^<]+)(?=<\/b><\/div>)/gi, function(m1,m2,m3){
// m2 matches "<div class='someClass'><b>"
// m3 matches "Some very long"
return m2 + m3.substr(0, MAX_LENGTH).trim();
})
console.info(shortText)
Here some documentation to the replace function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
A "cooler" Alternative:
If you pass the HTML Element that should be altered, to this short function checkChildren, all Child-Textnodes will be modified, trim, substr, ...
(it is a bit of an overkill, checking every node, if you know the final structure, but i just wanted to test it):
var elem = document.getElementById("test");
//define the max length of text nodes
const MAX_LENGTH = 13;
checkChildren(elem);
// check all children from parent element an limit the size of textNodes
function checkChildren(parent){
for(var i=0; i<parent.childNodes.length;i++){
var child = parent.childNodes[i];
switch(child.nodeType){
case Node.ELEMENT_NODE:
// recursive call
checkChildren(child);
break;
case Node.TEXT_NODE:
// modify textNode (Shorten and trim)
child.nodeValue = child.nodeValue.substr(0,MAX_LENGTH).trim();
break;
}
}
}
<div id="test" class='someClass'><b>Some very long text</b></div>
You can use $.parseHTML to convert this string into dom tree. Get the <b> node from this dom tree and change the text with the help of substr.

How to append string in jQuery without quotes?

Let's say we have a paragraph:
<p>txt0</p>
... and we want to append some text:
$("p").append("_txt1");
$("p").append("_txt2");
$("p").append("_txt3");
The result will be, as expected:
txt0_txt1_txt2_txt3
However if we inspect the result in browser, what it really is:
<p>
"txt0"
"_txt1"
"_txt2"
"_txt3"
</p>
There are 4 different strings that are only rendered as one. The problem is I'm creating a flash object dynamically and appending strings this way will not work because of the quotes. I really need it to be one continuous string like this:
<p>
txt0_txt1_txt2_txt3
</p>
Is there a way to append in such a way? Or to remove all the quotes afterwards?
PS. before you say to make one big string before appending, that won't work because the string is too big and for ex. it works in Chrome but not in Firefox or IExplorer (but that's a different issue).
Use text, otherwise you're appending a new TextNode everytime:
var $p = $('p');
$p.text('txt0');
$p.text($p.text() + '_txt1');
Or with textContent it's less confusing:
var p = $('p')[0];
p.textContent += 'txt0';
p.textContent += '_txt1';
...
You can manipulate the html inside the p-tag this way:
$('p').html($('p').html() + '_text');
My solution is similar to #DonnyDee's
$("p").append("_txt1");
$("p").append("_txt2");
$("p").append("_txt3");
$("p").html($("p").html());
Somehow .html knows how to remove the quotation marks where there are two strings together i.e. "txt0"
"_txt1" etc
afaik .text() is destructive, i.e. will replace html with text which is perhaps not what we want, although I agree for this example it would suffice.
$('p').html(function(index, oldHTML) { return oldHTML + '_text';});
looks like a good solution though. e.g.
$("p").append("_txt1");
$("p").append("_txt2");
$("p").append("_txt3");
$("p").html(function(index, oldHTML) { return oldHTML);

JS - Read Data Between XML Tags

I simply need to extract some info between two tags, in this case, <title>
For example:
...
<title>I Need This!</title>
...
And I simply need to be able to get the information between the tags. I was thinking using split(), however, I haven't been able to figure out how to cut all data before and after, and just catch the stuff in the title tags. As you can tell, I'm a beginner with text formatting. Thanks!
EDIT: An example of the type of file I'm looking through is here: https://gdata.youtube.com/feeds/api/videos/http://youtu.be/_OBlgSz8sSMg?v=2
I'm simply trying to take what's in the title tags to get the title of the video.
var text = '<title>I Need This!</title>',
match = text.match(/<title>([^<]*)<\/title>/),
youGotThis = match[1];
Here's the fiddle: http://jsfiddle.net/RPbSE/
DOM works on XML just as well as on HTML, so a simple
var titleNodeList = yourXMLDocument.getElementsByTagname('title');
var firstTitle = titleNodeList[0];
var titleTextNode = firstTitle.firstChild;
alert(titleTextNode);
should do.

Categories

Resources