How to manipulate particular character in DOM in JavaScript? - javascript

Suppose I have text called "Hello World" inside a DIV in html file. I want to manipulate sixth position in "Hello World" text and replace that result in DOM, like using innerHTML or something like that.
The way i do is
var text = document.getElementById("divID").innerText;
now somehow I got the text and and manipluate the result using charAt for particular position and replace the result in html by replacing the whole string not just that position element. What I want to ask is do we have to every time replace the whole string or is there a way using which we can extract the character from particular position and replace the result in that position only not the whole string or text inside the div.

If you just need to insert some text into an already existing string you should use replace(). You won't really gain anything by trying to replace only one character as it will need to make a new string anyway (as strings are immutable).
jsFiddle
var text = document.getElementById("divID").innerText;
// find and replace
document.getElementById("divID").innerText = text.replace('hello world', 'hello big world');

var newtext=text.replace(text[6],'b'); should work. Glad you asked, I didn't know that would work.
Curious that it works, it doesn't replace all instances of that character either which is odd... I guess accessing characters with bracket notation treats the character as some 'character' object, not just a string.
Don't quote me on that though.

Yes, you have to replace the entire string by another, since strings are immutable in JavaScript. You can in various ways hide this behind a function call, but in the end what happens is construction of a new string that replaces the old one.

Text with div's are actually text nodes and hence we will have to explicitly manipulate their content by replacing the older content with the newer one.
If you are using jQuery then you can refer to the below link for a possible technique:
[link Replacing text nodes with jQuery] http://www.bennadel.com/blog/2253-Replacing-Text-Nodes-With-jQuery.htm.
Behind the scenes, I would guess that jQuery still replaces the entire string ** for that text node**

Related

How do I replace string within quotes in javascript?

I have this in a javascript/jQuery string (This string is grabbed from an html ($('#shortcode')) elements value which could be changed if user clicks some buttons)
[csvtohtml_create include_rows="1-10"
debug_mode="no" source_type="visualizer_plugin" path="map"
source_files="bundeslander_staple.csv" include cols="1,2,4" exclude cols="3"]
In a textbox (named incl_sc) I have the value:
include cols="2,4"
I want to replace include_cols="1,2,4" from the above string with the value from the textbox.
so basically:
How do I replace include_cols values here? (include_cols="2,4" instead of include_cols="1,2,4") I'm great at many things but regex is not one of them. I guess regex is the thing to use here?
I'm trying this:
var s = $('#shortcode').html();
//I want to replace include cols="1,2,4" exclude cols="3"
//with include_cols="1,2" exclude_cols="3" for example
s.replace('/([include="])[^]*?\1/g', incl_sc.val() );
but I don't get any replacement at all (the string s is same string as $("#shortcode").html(). Obviously I'm doing something really dumb. Please help :-)
In short what you will need is
s.replace(/include cols="[^"]+"/g, incl_sc.val());
There were a couple problems with your code,
To use a regex with String.prototype.replace, you must pass a regex as the first argument, but you were actually passing a string.
This is a regex literal /regex/ while this isn't '/actually a string/'
In the text you supplied in your question include_cols is written as include cols (with a space)
And your regex was formed wrong. I recomend testing them in this website, where you can also learn more if you want.
The code above will replace the part include cols="1,2,3" by whatever is in the textarea, regardless of whats between the quotes (as long it doesn't contain another quote).
First of all I think you need to remove the quotes and fix a little bit the regex.
const r = /(include_cols=\")(.*)(\")/g;
s.replace(r, `$1${incl_sc.val()}$3`)
Basically, I group the first and last part in order to include them at the end of the replacement. You can also avoid create the first and last group and put it literally in the last argument of the replace function, like this:
const r = /include_cols=\"(.*)\"/g;
s.replace(r, `include_cols="${incl_sc.val()}"`)

Remove ads from a Webpage

I want to make chrome extension to remove some advertisments from webpages.
I think I have to learn to remove lines of text from a longer text to do that:
For example, given this text:
This is text that contains some string bla This is text that contains
some string bla This is text DELETEME some string bla This is text
that contains some string bla This is text that contains some string
bla
how can I remove the whole line of the text that contains the string DELETEME?
as text will be used document.body.InnerHTML; I want to take out some garbage :}
You could split the text into lines:
var lines = text.split('\n');
Then filter out the ones that contained that string:
lines.filter(function(line) {
return line.indexOf('DELETEME') === -1;
})
Then join that back together:
text = lines.filter(function(line) {
return line.indexOf('DELETEME') === -1;
}).join('\n');
For your project (creating a chrome extension to remove ads) you do not actually
need to manipulate text, you need to manipulate HTML code, or more specificall: the DOM, the document object model that represents the HTML code in your browser.
You can do this quite conveniently with jQuery.
Here's how you would delete ALL li's containting DELETEME:
$('li:contains(DELETEME)').remove();
here's a fiddle: http://jsfiddle.net/bjelline/RrCGw/
The best way to try this out is to open den developer tools in your browser and type the commands into the console, then you will see the effect immediately.
For example: google for "learn javascript" - you'll probably see an ad.
Look at the HTML source code to finde out that the id is inside a div with
id "tads". Now open the console and type in
$('#tads').remove();
And the ads will disappear.
You specifically asked about manipulating text. When manipulating text it's a good idea to learn about regular expressions - not just for JavaScript, you can use them in many programming languages.
If your whole text is stored in the variable string, you could do this:
string = string.replace(/.*DELETEME.*/, "XXXX");
to replace the line with XXXX. Just use an empty string as a replacement to empty it completely:
string = string.replace(/.*DELETEME.*/, "");
The ".*" stands for "any character, repeated as often as necessary", which matches
the text before and after DELETEME. This regular expression only works on one line, so text on other lines is not changed.
See http://jsfiddle.net/bjelline/Wc7ve/ for a working example.
But, as stated above: this is not the right tool for your project.

Unable to parse the JSON correctly

In the response of type application/x-javascript I am picking the required JSON portion in a varaible. Below is the JSON-
{
"__ra":1,
"payload":null,
"data":[
[
"replace",
"",
true,
{
"__html": "\u003Cspan class=\"highlight fsm\" id=\"u_c_0\">I want this text only\u003C\/span>"
}
]
]
}
From the references, which I got from Stackoverflow, I am able to pick the content inside data in the following way-
var temp = JSON.parse(resp).data;
But my aim is to get only the text part of __html value which is I want this text only . Somebody help.
First you have to access the object you targeted:
var html = JSON.parse(resp).data[0][3]._html;
But then the output you want is I want this text only
The html variable doesn't containt that text but some html where the content you're looking for is the text inside a span
If you accept including jQuery in your project you can access that content this way
var text = $(html).text();
To put it all together:
var html = JSON.parse(resp).data[0][3]._html;
var div = document.createElement("div");
div.innerHTML = html;
var text = div.textContent || div.innerText || "";
Kudos #Tim Down for this answer on cross-browser innerHTML: JavaScript: How to strip HTML tags from string?
First you'll need to be a bit more specific with that data to get to the string of text you want:
var temp = JSON.parse(resp).data[0][3]['__html'];
Next you'll need to search that string to extract the data you want. That will largely depend on the regularity of the response you are getting. In any case, you will probably need to use a regular expression to parse the string you get in the response.
In this case, you are trying to get the text within the <span> element in the string. If that was the case for all your responses, you could do something like:
var text = /<span[^>]*>([^<]*)<\/span>/.exec(temp)[1];
This very specifically looks for text within the opening and closing of one span tag that contains no other HTML tags.
The main part to look at in the expression here is the ([^<]*), which will capture any character that is not an opening angled bracket, <. Everything around this is looking for instances of <span> with optional attributes. The exec is the method you perform on the temp string to return a match and the [1] will give you the first and only capture (e.g. the text between the <span> tags).
You would need read up more about RegExp to find out how to do something more specific (or provide more specific information in your question about the pattern of response you are looking for). But's generally well worth reading up on regular expressions if you're going to be doing this kind of work (parsing text, looking for patterns and matches) because they are a very concise and powerful way of doing it, if a little confusing at first.

How can I split text on commas not within double quotes, while keeping the quotes?

So I'm trying to split a string in javacript, something that looks like this:
"foo","super,foo"
Now, if I use .split(",") it will turn the string into an array containing [0]"foo" [1]"super [2]foo"
however, I only want to split a comma that is between quotes, and if I use .split('","'), it will turn into [0]"foo [1]super,foo"
Is there a way I can split an element expressing delimiters, but have it keep certain delimiters WITHOUT having to write code to concatenate a value back onto the string?
EDIT:
I'm looking to get [0]"foo",[1]"super,foo" as my result. Essentially, the way I need to edit certain data, I need what is in [0] to never get changed, but the contents of [1] will get changed depending on what it contains. It will get concatenated back to look like "foo", "I WAS CHANGED" or it will indeed stay the same if the contents of [1] where not something that required a change
Try this:
'"foo","super,foo"'.replace('","', '"",""').split('","');
For the sake of discussion and benefit of everyone finding this page is search of help, here is a more flexible solution:
var text = '"foo","super,foo"';
console.log(text.match(/"[^"]+"/g));
outputs
['"foo"', '"super,foo"']
This works by passing the 'g' (global) flag to the RegExp instance causing match to return an array of all occurrences of /"[^"]"/ which catches "foo,bar", "foo", and even "['foo', 'bar']" ("["foo", "bar"]" returns [""["", "", "", ""]""].)

How do I extract the title value from a string using Javascript regexp?

I have a string variable which I would like to extract the title value in id="resultcount" element. The output should be 2.
var str = '<table cellpadding=0 cellspacing=0 width="99%" id="addrResults"><tr></tr></table><span id="resultcount" title="2" style="display:none;">2</span><span style="font-size: 10pt">2 matching results. Please select your address to proceed, or refine your search.</span>';
I tried the following regex but it is not working:
/id=\"resultcount\" title=['\"][^'\"](+['\"][^>]*)>/
Since var str = ... is Javascript syntax, I assume you need a Javascript solution. As Peter Corlett said, you can't parse HTML using regular expressions, but if you are using jQuery you can use it to take advantage of browser own parser without effort using this:
$('#resultcount', '<div>'+str+'</div>').attr('title')
It will return undefined if resultcount is not found or it has not a title attribute.
To make sure it doesn't matter which attribute (id or title) comes first in a string, take entire html element with required id:
var tag = str.replace(/^.*(<[^<]+?id=\"resultcount\".+?\/.+?>).*$/, "$1")
Then find title from previous string:
var res = tag.replace(/^.*title=\"(\d+)\".*$/, "$1");
// res is 2
But, as people have previously mentioned it is unreliable to use RegEx for parsing html, something as trivial as different quote (single instead of double quote) or space in "wrong" place will brake it.
Please see this earlier response, entitled "You can't parse [X]HTML with regex":
RegEx match open tags except XHTML self-contained tags
Well, since no one else is jumping in on this and I'm assuming you're just looking for a value and not trying to create a parser, I'll give you what works for me with PCRE. I'm not sure how to put it into the java format for you but I think you'll be able to do that.
span id="resultcount" title="(\d+)"
The part you're looking to get is the non-passive group $1 which is the '\d+' part. It will get one or more digits between the quote marks.

Categories

Resources