Passing a parameter to function with single quote - javascript

How do I pass a parameter to a javascript function with ' included
var name ="Lauren O'Donald";
var htmlAnch='<a onclick="javascript:selectEmployee(1100,"'+name+'");return false;"
href="javascript:void(0);">O'Donald, Lauren</a>';
$(document).append($(htmlAnch));
The javascript function is not executing since the name 'Lauren O'Donald' contains single quote.
How can I add a parameter with ' and prepare dynamic html to make it work?
Here is the dynamic code to generate
var rows = new StringBuffer();
$(data).each(function(index) {
rows.append(String.format('<tr><td><a href="No.aspx"
onclick="javascript:selectEmployee({3},\"{1} {2}\");return
false;">{0}</a></td></tr>',
String.format("{0}, {1}", this.Surname, this.FirstName),
this.Surname,
this.FirstName,
this.Id
));
});

You can escape quotes/characters by prepending \ to it:
var string = 'my string with "double quotes" and \'single quotes\'';
var string = "my string with 'single quotes' and \"double quotes\"";
// ^ ^
Using a dynamic string:
var foo = "bar with 'quotes'";
var string = 'my string with "double quotes" and ' + foo.replace(/'/g, "\\'");
//my string with "double quotes" and bar with \'quotes\'

You can escape it using \:
var htmlAnch='<a onclick="javascript:selectEmployee(1100,\'Lauren O\'Donald\');return false;"
href="javascript:void(0);">O\'Donald, Lauren</a>';
However as you've tagged this question with jQuery,a better solution is to hook up an event to the element and use data-* attributes to store the relevant information, which will avoid the use of ugly onX attributes. Try this:
var $htmlAnch = $('<a />' {
text: "O'Donald, Lauren" ,
data-id: 1100,
data-name: "Lauren O'Donald"
}).click(function(e) {
e.preventDefault();
selectEmployee($(this).data('id'), $(this).data('name'));
});
$(document).append($htmlAnch);

Write your own function to return a escaped string. Demo
Pass your string as argument to this function and you will get escaped string. You can also add more characters to blocklist if you want to escape some more characters
function remove_quotes(values1)
{
var values = values1.toString();
var str = "";
var blockList = ['"','\'','\\']; // This is the list of key words to be escaped
var flag = 0;
for(var i = 0;i<values.length;i++)
{
for(var j=0;j<blockList.length;j++)
{
if(values[i] == blockList[j])
{
flag = 1;
break;
}
}
if(flag == 0)
str += values[i];
else
{
str += '\\';
str += values[i];
flag = 0;
}
}
return str;
}

try something like this
var htmlAnch='<a onclick="javascript:selectEmployee(1100,\'Lauren O\'Donald\');return false;" href="javascript:void(0);">O\'Donald, Lauren</a>';

In .aspx file you can do like as below:
<a data-open="editTemplateOverrideModal" onClick="populateUp
dateModal('<%#Server.HtmlEncode(Convert.ToString(DataBinder.Eval(Container.DataItem, "Description")).**Replace("'", "\'")) %>')**">

Related

Javascript: Convert chars like ' to UTF8 [duplicate]

This question already has answers here:
Unescape HTML entities in JavaScript?
(33 answers)
Closed 5 years ago.
How do I encode and decode HTML entities using JavaScript or JQuery?
var varTitle = "Chris&apos; corner";
I want it to be:
var varTitle = "Chris' corner";
I recommend against using the jQuery code that was accepted as the answer. While it does not insert the string to decode into the page, it does cause things such as scripts and HTML elements to get created. This is way more code than we need. Instead, I suggest using a safer, more optimized function.
var decodeEntities = (function() {
// this prevents any overhead from creating the object each time
var element = document.createElement('div');
function decodeHTMLEntities (str) {
if(str && typeof str === 'string') {
// strip script/html tags
str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
element.innerHTML = str;
str = element.textContent;
element.textContent = '';
}
return str;
}
return decodeHTMLEntities;
})();
http://jsfiddle.net/LYteC/4/
To use this function, just call decodeEntities("&") and it will use the same underlying techniques as the jQuery version will—but without jQuery's overhead, and after sanitizing the HTML tags in the input. See Mike Samuel's comment on the accepted answer for how to filter out HTML tags.
This function can be easily used as a jQuery plugin by adding the following line in your project.
jQuery.decodeEntities = decodeEntities;
You could try something like:
var Title = $('<textarea />').html("Chris&apos; corner").text();
console.log(Title);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
JS Fiddle.
A more interactive version:
$('form').submit(function() {
var theString = $('#string').val();
var varTitle = $('<textarea />').html(theString).text();
$('#output').text(varTitle);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
<fieldset>
<label for="string">Enter a html-encoded string to decode</label>
<input type="text" name="string" id="string" />
</fieldset>
<fieldset>
<input type="submit" value="decode" />
</fieldset>
</form>
<div id="output"></div>
JS Fiddle.
Like Robert K said, don't use jQuery.html().text() to decode html entities as it's unsafe because user input should never have access to the DOM. Read about XSS for why this is unsafe.
Instead try the Underscore.js utility-belt library which comes with escape and unescape methods:
_.escape(string)
Escapes a string for insertion into HTML, replacing &, <, >, ", `, and ' characters.
_.escape('Curly, Larry & Moe');
=> "Curly, Larry & Moe"
_.unescape(string)
The opposite of escape, replaces &, <, >, ", ` and ' with their unescaped counterparts.
_.unescape('Curly, Larry & Moe');
=> "Curly, Larry & Moe"
To support decoding more characters, just copy the Underscore unescape method and add more characters to the map.
Original author answer here.
This is my favourite way of decoding HTML characters. The advantage of using this code is that tags are also preserved.
function decodeHtml(html) {
var txt = document.createElement("textarea");
txt.innerHTML = html;
return txt.value;
}
Example: http://jsfiddle.net/k65s3/
Input:
Entity: Bad attempt at XSS:<script>alert('new\nline?')</script><br>
Output:
Entity: Bad attempt at XSS:<script>alert('new\nline?')</script><br>
Here's a quick method that doesn't require creating a div, and decodes the "most common" HTML escaped chars:
function decodeHTMLEntities(text) {
var entities = [
['amp', '&'],
['apos', '\''],
['#x27', '\''],
['#x2F', '/'],
['#39', '\''],
['#47', '/'],
['lt', '<'],
['gt', '>'],
['nbsp', ' '],
['quot', '"']
];
for (var i = 0, max = entities.length; i < max; ++i)
text = text.replace(new RegExp('&'+entities[i][0]+';', 'g'), entities[i][1]);
return text;
}
here is another version:
function convertHTMLEntity(text){
const span = document.createElement('span');
return text
.replace(/&[#A-Za-z0-9]+;/gi, (entity,position,text)=> {
span.innerHTML = entity;
return span.innerText;
});
}
console.log(convertHTMLEntity('Large < £ 500'));
Inspired by Robert K's solution, this version does not strip HTML tags, and is just as secure.
var decode_entities = (function() {
// Remove HTML Entities
var element = document.createElement('div');
function decode_HTML_entities (str) {
if(str && typeof str === 'string') {
// Escape HTML before decoding for HTML Entities
str = escape(str).replace(/%26/g,'&').replace(/%23/g,'#').replace(/%3B/g,';');
element.innerHTML = str;
if(element.innerText){
str = element.innerText;
element.innerText = '';
}else{
// Firefox support
str = element.textContent;
element.textContent = '';
}
}
return unescape(str);
}
return decode_HTML_entities;
})();
jQuery provides a way to encode and decode html entities.
If you use a "<div/>" tag, it will strip out all the html.
function htmlDecode(value) {
return $("<div/>").html(value).text();
}
function htmlEncode(value) {
return $('<div/>').text(value).html();
}
If you use a "<textarea/>" tag, it will preserve the html tags.
function htmlDecode(value) {
return $("<textarea/>").html(value).text();
}
function htmlEncode(value) {
return $('<textarea/>').text(value).html();
}
To add yet another "inspired by Robert K" to the list, here is another safe version which does not strip HTML tags. Instead of running the whole string through the HTML parser, it pulls out only the entities and converts those.
var decodeEntities = (function() {
// this prevents any overhead from creating the object each time
var element = document.createElement('div');
// regular expression matching HTML entities
var entity = /&(?:#x[a-f0-9]+|#[0-9]+|[a-z0-9]+);?/ig;
return function decodeHTMLEntities(str) {
// find and replace all the html entities
str = str.replace(entity, function(m) {
element.innerHTML = m;
return element.textContent;
});
// reset the value
element.textContent = '';
return str;
}
})();
Inspired by Robert K's solution, strips html tags and prevents executing scripts and eventhandlers like: <img src=fake onerror="prompt(1)">
Tested on latest Chrome, FF, IE (should work from IE9, but haven't tested).
var decodeEntities = (function () {
//create a new html document (doesn't execute script tags in child elements)
var doc = document.implementation.createHTMLDocument("");
var element = doc.createElement('div');
function getText(str) {
element.innerHTML = str;
str = element.textContent;
element.textContent = '';
return str;
}
function decodeHTMLEntities(str) {
if (str && typeof str === 'string') {
var x = getText(str);
while (str !== x) {
str = x;
x = getText(x);
}
return x;
}
}
return decodeHTMLEntities;
})();
Simply call:
decodeEntities('<img src=fake onerror="prompt(1)">');
decodeEntities("<script>alert('aaa!')</script>");
Here is a full version
function htmldecode(s){
window.HTML_ESC_MAP = {
"nbsp":" ","iexcl":"¡","cent":"¢","pound":"£","curren":"¤","yen":"¥","brvbar":"¦","sect":"§","uml":"¨","copy":"©","ordf":"ª","laquo":"«","not":"¬","reg":"®","macr":"¯","deg":"°","plusmn":"±","sup2":"²","sup3":"³","acute":"´","micro":"µ","para":"¶","middot":"·","cedil":"¸","sup1":"¹","ordm":"º","raquo":"»","frac14":"¼","frac12":"½","frac34":"¾","iquest":"¿","Agrave":"À","Aacute":"Á","Acirc":"Â","Atilde":"Ã","Auml":"Ä","Aring":"Å","AElig":"Æ","Ccedil":"Ç","Egrave":"È","Eacute":"É","Ecirc":"Ê","Euml":"Ë","Igrave":"Ì","Iacute":"Í","Icirc":"Î","Iuml":"Ï","ETH":"Ð","Ntilde":"Ñ","Ograve":"Ò","Oacute":"Ó","Ocirc":"Ô","Otilde":"Õ","Ouml":"Ö","times":"×","Oslash":"Ø","Ugrave":"Ù","Uacute":"Ú","Ucirc":"Û","Uuml":"Ü","Yacute":"Ý","THORN":"Þ","szlig":"ß","agrave":"à","aacute":"á","acirc":"â","atilde":"ã","auml":"ä","aring":"å","aelig":"æ","ccedil":"ç","egrave":"è","eacute":"é","ecirc":"ê","euml":"ë","igrave":"ì","iacute":"í","icirc":"î","iuml":"ï","eth":"ð","ntilde":"ñ","ograve":"ò","oacute":"ó","ocirc":"ô","otilde":"õ","ouml":"ö","divide":"÷","oslash":"ø","ugrave":"ù","uacute":"ú","ucirc":"û","uuml":"ü","yacute":"ý","thorn":"þ","yuml":"ÿ","fnof":"ƒ","Alpha":"Α","Beta":"Β","Gamma":"Γ","Delta":"Δ","Epsilon":"Ε","Zeta":"Ζ","Eta":"Η","Theta":"Θ","Iota":"Ι","Kappa":"Κ","Lambda":"Λ","Mu":"Μ","Nu":"Ν","Xi":"Ξ","Omicron":"Ο","Pi":"Π","Rho":"Ρ","Sigma":"Σ","Tau":"Τ","Upsilon":"Υ","Phi":"Φ","Chi":"Χ","Psi":"Ψ","Omega":"Ω","alpha":"α","beta":"β","gamma":"γ","delta":"δ","epsilon":"ε","zeta":"ζ","eta":"η","theta":"θ","iota":"ι","kappa":"κ","lambda":"λ","mu":"μ","nu":"ν","xi":"ξ","omicron":"ο","pi":"π","rho":"ρ","sigmaf":"ς","sigma":"σ","tau":"τ","upsilon":"υ","phi":"φ","chi":"χ","psi":"ψ","omega":"ω","thetasym":"ϑ","upsih":"ϒ","piv":"ϖ","bull":"•","hellip":"…","prime":"′","Prime":"″","oline":"‾","frasl":"⁄","weierp":"℘","image":"ℑ","real":"ℜ","trade":"™","alefsym":"ℵ","larr":"←","uarr":"↑","rarr":"→","darr":"↓","harr":"↔","crarr":"↵","lArr":"⇐","uArr":"⇑","rArr":"⇒","dArr":"⇓","hArr":"⇔","forall":"∀","part":"∂","exist":"∃","empty":"∅","nabla":"∇","isin":"∈","notin":"∉","ni":"∋","prod":"∏","sum":"∑","minus":"−","lowast":"∗","radic":"√","prop":"∝","infin":"∞","ang":"∠","and":"∧","or":"∨","cap":"∩","cup":"∪","int":"∫","there4":"∴","sim":"∼","cong":"≅","asymp":"≈","ne":"≠","equiv":"≡","le":"≤","ge":"≥","sub":"⊂","sup":"⊃","nsub":"⊄","sube":"⊆","supe":"⊇","oplus":"⊕","otimes":"⊗","perp":"⊥","sdot":"⋅","lceil":"⌈","rceil":"⌉","lfloor":"⌊","rfloor":"⌋","lang":"〈","rang":"〉","loz":"◊","spades":"♠","clubs":"♣","hearts":"♥","diams":"♦","\"":"quot","amp":"&","lt":"<","gt":">","OElig":"Œ","oelig":"œ","Scaron":"Š","scaron":"š","Yuml":"Ÿ","circ":"ˆ","tilde":"˜","ndash":"–","mdash":"—","lsquo":"‘","rsquo":"’","sbquo":"‚","ldquo":"“","rdquo":"”","bdquo":"„","dagger":"†","Dagger":"‡","permil":"‰","lsaquo":"‹","rsaquo":"›","euro":"€"};
if(!window.HTML_ESC_MAP_EXP)
window.HTML_ESC_MAP_EXP = new RegExp("&("+Object.keys(HTML_ESC_MAP).join("|")+");","g");
return s?s.replace(window.HTML_ESC_MAP_EXP,function(x){
return HTML_ESC_MAP[x.substring(1,x.length-1)]||x;
}):s;
}
Usage
htmldecode("∑ >€");
Injecting untrusted HTML into the page is dangerous as explained in How to decode HTML entities using jQuery?.
One alternative is to use a JavaScript-only implementation of PHP's html_entity_decode (from http://phpjs.org/functions/html_entity_decode:424). The example would then be something like:
var varTitle = html_entity_decode("Chris&apos; corner");
A more functional approach to #William Lahti's answer:
var entities = {
'amp': '&',
'apos': '\'',
'#x27': '\'',
'#x2F': '/',
'#39': '\'',
'#47': '/',
'lt': '<',
'gt': '>',
'nbsp': ' ',
'quot': '"'
}
function decodeHTMLEntities (text) {
return text.replace(/&([^;]+);/gm, function (match, entity) {
return entities[entity] || match
})
}
I know I'm a bit late to the game, but I thought I might provide the following snippet as an example of how I decode HTML entities using jQuery:
var varTitleE = "Chris&apos; corner";
var varTitleD = $("<div/>").html(varTitleE).text();
console.log(varTitleE + " vs. " + varTitleD);​​​​​​​​​​​
Don't forget to fire-up your inspector/firebug to see the console results -- or simply replace console.log(...) w/alert(...)
That said, here's what my console via the Google Chrome inspector read:
Chris&apos; corner vs. Chris' corner
Because #Robert K and #mattcasey both have good code, I thought I'd contribute here with a CoffeeScript version, in case anyone in the future could use it:
String::unescape = (strict = false) ->
###
# Take escaped text, and return the unescaped version
#
# #param string str | String to be used
# #param bool strict | Stict mode will remove all HTML
#
# Test it here:
# https://jsfiddle.net/tigerhawkvok/t9pn1dn5/
#
# Code: https://gist.github.com/tigerhawkvok/285b8631ed6ebef4446d
###
# Create a dummy element
element = document.createElement("div")
decodeHTMLEntities = (str) ->
if str? and typeof str is "string"
unless strict is true
# escape HTML tags
str = escape(str).replace(/%26/g,'&').replace(/%23/g,'#').replace(/%3B/g,';')
else
str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '')
str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '')
element.innerHTML = str
if element.innerText
# Do we support innerText?
str = element.innerText
element.innerText = ""
else
# Firefox
str = element.textContent
element.textContent = ""
unescape(str)
# Remove encoded or double-encoded tags
fixHtmlEncodings = (string) ->
string = string.replace(/\&#/mg, '&#') # The rest, for double-encodings
string = string.replace(/\"/mg, '"')
string = string.replace(/\&quote;/mg, '"')
string = string.replace(/\_/mg, '_')
string = string.replace(/\'/mg, "'")
string = string.replace(/\"/mg, '"')
string = string.replace(/\>/mg, '>')
string = string.replace(/\</mg, '<')
string
# Run it
tmp = fixHtmlEncodings(this)
decodeHTMLEntities(tmp)
See https://jsfiddle.net/tigerhawkvok/t9pn1dn5/7/ or https://gist.github.com/tigerhawkvok/285b8631ed6ebef4446d (includes compiled JS, and is probably updated compared to this answer)
To do it in pure javascript without jquery or predefining everything you can cycle the encoded html string through an elements innerHTML and innerText(/textContent) properties for every decode step that is required:
<html>
<head>
<title>For every decode step, cycle through innerHTML and innerText </title>
<script>
function decode(str) {
var d = document.createElement("div");
d.innerHTML = str;
return typeof d.innerText !== 'undefined' ? d.innerText : d.textContent;
}
</script>
</head>
<body>
<script>
var encodedString = "<p>name</p><p><span style=\"font-size:xx-small;\">ajde</span></p><p><em>da</em></p>";
</script>
<input type=button onclick="document.body.innerHTML=decode(encodedString)"/>
</body>
</html>
I think that is the exact opposite of the solution chosen.
var decoded = $("<div/>").text(encodedStr).html();
Try it :)

find text in string and replace it

I have a variable which contains a string expression. This expression have the pattern:
propery_expression operator value
proeprty_expression can look like:
World
World/Name
City/Name
I want to find text after /, and If it exists, and replace with custom text. How can I do this?
With a regex, for example this one :
yourString.replace(/\/\S+/, '/the new stuff...');
In the console :
> var cityName = 'Djakarta';
> var line = 'World/Name Something SomethingElse';
> line.replace(/\/\S+/, '/' + cityName);
"World/Djakarta Something SomethingElse"
You can use this to do complex search and replace operations. Details on Mozilla's documentation
You could try this
var the_string = "City/Name";
var word = "New";
var result = the_string.substring(0, the_string.lastIndexOf('/') + 1);
alert(result + word);
You can try this:
var str = 'World';
alert(rep(str));
function rep(str)
{
if(str.indexOf('/')>-1)//present
{
alert(str.substring(str.lastIndexOf('/') + 1,str.length));
var res = str.replace(str.substring(str.lastIndexOf('/') + 1,str.length),'custom_word');
return res;
}
else{
alert(' / not present');
return str;
}
}
DEMO
Note: If text present after / then it replace it with "custom_word".
In addition to Mathias's answer, you could use RegEx together with a function, like so:
var myString;
.
.
.
myString.replace(/\/(\S+)/g, function (found, value) {
// found == "City/NewYork"
// value == "NewYork"
return found + "Altered";
}
This, for example, will change every "x/y" with "x/yAltered"

String manipulation using javascript

I am working on some string manipulations using javascript.I have a senario where i need to do a search in the string and remove certain words.
Here is my senario:
When i click 'Click me' it should look for the word in the input from the string variable,
and if matching found it should remove that word from the input.
Here is my sepecial senario, while removing the word from the input, it should remove the : and the integer value and comma (if available) which is there before the matching word.
In my example input is 1:first user,2:second user in the text box
i need the output as 2:second user
How can i achive this
<input id='textinput' type='text' value='1:first user,2:second user'></input>
<div class='click'>Click me</div>
$(document).ready(function () {
$(".click").click(function () {
var string = 'first user';
$('#textinput').val().replace(/string/g, '');
});
});
i have created a fiddle http://jsfiddle.net/h9D5W/
EDIT
here my variable string contains only user names i can't append id's with user names for example 1:first user, so the exact match will not be there in the string variable.
I have removed the starting digits, underscore and ending comma.
$(document).ready(function () {
$(".click").click(function () {
var string = 'first user';
var re = new RegExp('\\d:*'+string+',*',"g");
var text = $('#textinput').val().replace(re, '');;
$('#textinput').val(text);
});
});
Check the demo
http://jsfiddle.net/yKfur/1/
In your JavaScript code, string is a variable. You'd need to initiate the RegExp class to generate the pattern:
Also, please refrain from using variable name like string. It's the name of a global object.
var s = 'first user';
var x = $( '#textinput' ).val().replace(new RegExp(s, 'g'), '');
// use the new variable x as you wish
You should use RegExp, You need to initialize it with string variable.
Use
$(".click").click(function () {
var string = 'first user';
var re = new RegExp(string,"g"); //initialize RegExp
var text = $('#textinput').val().replace(re, ''); //Get replaced text
$('#textinput').val(text); //Reset its value
});
DEMO
EDIT
here i cant use 1:first user in the variable
$(".click").click(function () {
var arr = $('#textinput').val().split(','); //Here used split method to split string ',' as deliminator
$('#textinput').val(arr[arr.length - 1]);
});
DEMO
You can use a regular expression like:
var text = '1:first user,2:second user,3:third user';
var s = 'first user';
var re = new RegExp('^\\d+:' + s + ',?|,\\d+:' + s + '\\b');
text.replace(re, '') // '2:second user,3:third user'
I'm sure there's a shorter one though.
I have updated your fiddle
first, i split your string into array
var inputArr = ($('#textinput').val()).split(',');
so i can check each set of words using for loop,
for (i = 0; i < inputArr.length; i++) {
if (inputArr[i].indexOf(string) == -1) {
newStr = newStr + inputArr[i] + ',';
}
}
then i set the new value using substring to eliminate the last comma appended.
$('#textinput').val(newStr.substring(0, newStr.length - 1));

Regular expression to escape double quotes within double quotes

I have a string that needs to be parsed as JSON.
The problem is, it may sometimes contain double quotes, causing errors in parsing.
For example:
{
"id_clients":"58844",
"id_clients_name" : ""100" test"qw"
}
I need a regex to replace any double quotes between the opening and closing " with a \".
Thanks.
I tried it just for fun, even though it is certainly better to fix the generator. This might work in your case, or at least inspire you:
You can try it here
$( function()
{
var myString = "{ \"na\"\"me\": \"va\"lue\", \"tes\"\"t\":\"ok\" }";
var myRegexp = /\s*\"([\w\"]+)\"\s*[,}:]/g;
var match;
var matches = [];
// Save all the matches
while((match = myRegexp.exec(myString)) !== null)
{
matches.push(match[1]);
console.log(match[1]);
}
// Process them
var newString = myString;
for (var i=0; i<matches.length; i++)
{
var newVal = matches[i].replace(/\"/g, '\\\"');
newString = newString.replace(matches[i], newVal);
}
alert(myString + "\n" + newString);
}
);
You can try, although this will work only for the opening tags :
.replace(/\"\"/g, '\\""');

Remove a letter(:) from a string

I have strings like Name:, Call:, Phone:....and so on in my table. I am learning jQuery and was able to access the text. My tutorial has used trim() to remove any whitespaces. But I want o remove ":" from the end of each string (and yes, it always lies in the end after calling trim() method). So how to achieve it.
Its my code:
<script type="text/javascript">
$(function ()
{
$(':input[type=text], textarea').each
(
function ()
{
var newText = 'Please enter your ' +
$(this).parent().prev().text().toLowerCase().trim();
$(this).attr('value', newText);
}).one('focus', function ()
{
this.value = '', this.className = ''
}).addClass('Watermark').css('width', '300px');
});
</script>
trim(":") did not help...
You can replace all : characters:
var str = '::a:sd:';
str = str.replace(/:/g,''); // str = 'asd';
Or use a handy rtrim() function:
String.prototype.rtrim = function(character) {
var re = new RegExp(character + '*$', 'g');
return this.replace(re, '');
};
var str = '::a:sd:';
str = str.rtrim(':'); // str = '::a:sd';
In this case just use the plain old JavaScript replace or substr methods.
You can also use a regular expression that looks for colon as the last character (the character preceding the regexp end-of-string anchor "$").
"hi:".replace(/:$/, "")
hi
"hi".replace(/:$/, "")
hi
"h:i".replace(/:$/, "")
h:i
This is a simplified, inline version of the rtrim function in Blender's answer.
EDIT: Here is a test fiddle for Blender's corrected rtrim function. Note that his RegExp will delete multiple occurrences of the specified character if the string ends with multiple instances of it consecutively (example bolded below).
http://jsfiddle.net/fGrPb/5/
input = '::a:sd:' output = '::a:sd'; input = 'hi:' output = 'hi'; input = 'hi:::' output = 'hi'; input = 'hi' output = 'hi'; input = 'h:i' output = 'h:i'
To chop the last character of a string use string.slice(0,-1)
You can use a regular expression to remove the colon (:).
Replace one instance:
var with_colon = 'Stuff:';
var regex = /([^:]*):/;
var without_colon = regex.exec(with_colon)[1];
alert(without_colon);
Result: Stuff
Replace all instances:
var with_colon = 'Stuff: Things:';
var without_colon = with_colon.replace(/([^:]*):/g,'$1');
alert(without_colon);
Result: Stuff Things
var myStr = "something:";
myStr = myStr.slice(0, -1);
var a="name:";
var b=a.split(":");
alert(b[0]);
one way is to use lastIndexOf
var str='Name:, Call:, Phone:';
var index=str.lastIndexOf(":");
alert(index);
var s=str.substring(0,index);
alert(s);
DEMO
This checks if the last character is a colon. If it is, the last character is removed.
if (str[str.length - 1] === ":") {
str = str.slice(0, -1);
}
If there can be multiple trailing colons, you can replace if with while, like this:
while (str[str.length - 1] === ":") {
str = str.slice(0, -1);
}
You could even make a generic trim function that accepts a string and a character and trims trailing instances of that character:
var trim = function(str, chr) {
while (str[str.length - 1] === ":") {
str = str.slice(0, -1);
}
return str;
}
function trim(str) {
str = str.replace(/^:*/,"");
return str.replace(/:*$/,"");
}
str = str.substring(0,str.lastIndexOf(":"));
Note that this removes everything from the last : to the end of the string (for example, any whitespace after the :).

Categories

Resources