JavaScript replace() one html entity with another - javascript

I want to get some textarea text and replace all bullet point html entities • with ·.
The usual approach str.replace(/•/g,"·"); doesn't work.
Any advice would be appreciated.

When you're getting the text value back from the textarea, it has already been converted to its actual character. To do a string replacement on that string, either
convert all characters to their html entity counterparts, then proceed with what you're doing or
use the character in the regex directly.
Here's an example of the second approach.
var newText = oldText.replace(/•/g, "");
You can fiddle with an example here.
If you want to go with the first approach, see this question and its answers for ways to convert characters in a piece of text to their corresponding html entities.

If you want to do this without jQuery:
var myTextarea = document.getElementById('id_of_your_textarea');
myTextarea.value = myTextarea.value.replace(/•/g, '·');
jQuery:
$("#myTextarea").val( $("#myTextarea").val().replace(/•/g, '·') );
.val() will get the value from an input element, .val('str') will set a value.

Related

Escaping string using JavaScript before populating form input

I have this code where I grab an attribute value and load it into a form, the headline line can look something like:
Welcome to America's best valued whatever
But when using this escape function, the string is cut off at the apostrophe,
var headline = escape($(this).attr("data-headline"));
//populate the textbox
$(e.currentTarget).find('input[name="headline"]').val(headline);
I've also tried using the solutions here: HtmlSpecialChars equivalent in Javascript? with no luck.
How can I populate my input and keep apostrophe's/quotes?
Just use
$(this).find('input[name="headline"]').val(this.dataset.headline);
No need for any escaping.
However, notice that escape does not cut off apostrophes, it replaces them with %27. If your current code does not work with apostrophes in the headline, make sure that the markup containing the data-headline attribute is properly escaped by whatever tool is creating it.
var headline = $(this).attr("data-headline").replace(/'/g, '%27');
//populate the textbox
$(e.currentTarget).find('input[name="headline"]').val(unescape(headline));
If browser compatibility is important, dataset is only available IE11+ https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset#Browser_compatibility

Regular expression for selecting part of string and excluding another part of string

I have one string as variable and I want to use str.replace to replace each search string hit with <span style="..."> + search string + </span>. The problem is that I do this in loop in which the search string changes and some times the search string is similar to span or style. When this happens the result could be something like this <span <span style="...">style</span>="...">search string</span> which is catastrophic. So I need someone to help my by creating regular expression which selects the search string and excludes <span style="..."> and <span> or give me an idea how to solve this.
Here is parth from my code which needs to be changed:
if ($("#search_criteria option:selected").text() == lng("note_text_txt", "note_text_txt") && $("#search_note").val().trim() != "")
{
var SearchArr = $("#search_note").val().split(" ");
for (i = 0; i < SearchArr.length;i++)
{
data["text"] = data["text"].replace(RegExp(SearchArr[i], 'g'), "<span style='color:red;'>" + SearchArr[i] + "</span>");
}
}
var SearchArr has words which need to be found in data["text"] and replaced.
I'm posting this answer to provide you a regex to match and get content between your <span>...</span>.
But, I'm not sure what exactly you want to do. You can post some comments to help me understand your fully needs so I can update the answer to give an accurate post.
For the moment, I leave you the regex and a demo below.
Matching and get content regex
<span.*?>(.*?)<\/span>
Here you can see a working example
On the other hand, you can use another option for replace the content.
Replace content regex
(<span.*?>)(.*?)(<\/span>)
Here you have the working demo
Hope to help.
If you are already using JQuery, you could replace the actual tag contents using selectors of the library.
I would think like this:
$(data['text']).find('*:contains(SearchArr[i])').text(function(index, text) {
return text.replace(SearchArr[i], '<span>');
});
Take this as an idea and example. In an actual use you should specify better the elements above selected by *. The 'all' selector combined with :contains would take a big hit on the performance.
Edit:
It will work with your plain text just as well. If you provide valid HTML for a constructor of JQuery object, the DOM element packed in JQuery object gets created and you can operate on it in any way you would on any one selected from the document. Have a look at the following example: http://jsfiddle.net/Vk7N3/1/

Text Replacement With RegEx

I am using Sublime Text to write some Javascript and need to do a simple text replacement in the editor in order to set code up. I can do it manually but I figured there must be a way to have the replacement occur automatically with RegEx. I've used RegEx a bunch before but have never used it to grab data from one part of the code to reference and edit another part of the code. For example, I have this:
var example_1 = 836;
var example_2 = 837;
var example_3 = 838;
var example_4 = 846;
And then I have this:
SELECT_122=836
SELECT_143=837
SELECT_144=838
SELECT_145=846
I want these to use the corresponding values and format them like this:
SELECT_122: example_1,
SELECT_143: example_2,
SELECT_144: example_3,
SELECT_145: example_4
Note that I'm updating the equal signs to colons with spaces so I figured doing all these changes could be done with some sort of search and replace. I have a large amount of these so I figured it would be best to learn how to do this if it's possible.
I don't have SublimeText, but you said in a comment that you want to do it through a text editor. Here is what works for me in EditPad Pro, it may work in Sublime.
Search:
(?s)(var (example_\d++) = (\d++).*?SELECT_\d++)=\3
Replace:
\1: \2,
Then I click "Replace". This will replace the first instance (SELECT_122=836) with "SELECT_122: example_1,"
Then I click "Replace Next" multiple times, and the SELECT_ strings are left looking like this:
SELECT_122: example_1,
SELECT_143: example_2,
SELECT_144: example_3,
SELECT_145: example_4,
Is this what you want?
Hope the regex and replacement string at least get you started. :)

how to remove single quote from the value of hidden field in javascript

I am reading hidden field value using javascript. The value I am getting is within single quote( '78963' ). I can i remove this single quote ? I want the value without single quote( 78963 ). Please help me to solve the problem.
I guess you simply want to convert your string value to numeric.
Just use parseInt():
parseInt("78963", 10); // 78963
If the value pretends to be floating, there is parseFloat() method:
parseFloat("78963.1"); // 78963.1
And one more shortcut to make casting:
+"78963"; // 78963
In case if you simply want to replace single quotes, you may use:
"'78963'".replace(/'/g, ""); // "78963"
(as stated by others) or do tricky split:
"'78963'".split("'")[1]; // "78963"
You can use .replace() function on strings: http://www.w3schools.com/jsref/jsref_replace.asp
str.substr(1, str.length - 2);
Just $('#element').val(), you will get exact value. here element will be the id of hidden box.
If it's true that the value of the hidden input field contains single quotes, the (in my opinion) best answer is the one which JamesAllardice put in a comment:
yourValue.replace(/'/g, "");

Selecting and wrapping all occurences of a certain string with jQuery

In a list of footnote references for an article, I want to select all occurences of "(en)" and wrap them in some so that I can apply bold style to them as well as a right margin.
How to do that with jQuery ?
lets say you can get all your data into a string:
var myString = $('#footnotes').html();
Since you don't need regex you can split into an array and rejoin.. ex:
var newString = myString.split("(en)").join("<span class='en-element'>(en)</span>");
$('#footnotes').html(newString);
Using regex to find the "(en)"'s, and then using string.replace to replace them with the content you want.
I know when to use regex but am not too familiar with it's sintaxys, so sorry for not providing the exact code, take a look at this post in which they tried to do the same but finding and replacing it with \n
jQuery javascript regex Replace <br> with \n

Categories