最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Passing variable with single quote in javascript - Stack Overflow

programmeradmin1浏览0评论

I have an onClick call on a link:

<a onClick="fomateName('Andrew Dsouza')"> //this is working good

The problem is the variable inside fomateName would contain single quotes and my fomateName Takes a variable like

var a='Andrew D'souza'. Need to format a variable present with single quote Ex;

<a onClick="fomateName('a')"> which turns to 

<a onClick="fomateName('Andrew D'souza')"> //this is not working ,because present of single quote

Any Idea how to pass text with proper quotes in a javascript.

with single quote not the name actually

I have an onClick call on a link:

<a onClick="fomateName('Andrew Dsouza')"> //this is working good

The problem is the variable inside fomateName would contain single quotes and my fomateName Takes a variable like

var a='Andrew D'souza'. Need to format a variable present with single quote Ex;

<a onClick="fomateName('a')"> which turns to 

<a onClick="fomateName('Andrew D'souza')"> //this is not working ,because present of single quote

Any Idea how to pass text with proper quotes in a javascript.

with single quote not the name actually

Share Improve this question edited Jan 8, 2013 at 9:27 saum22 asked Jan 8, 2013 at 9:14 saum22saum22 88212 silver badges28 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 2

Try:

<a onClick="fomateName('Andrew D\'souza')"> <!-- this will work -->

\ use backslashes to escape '

Lets say if you have function like this =>

function fomateName(txt){
    alert(txt);
}

and invoking it from anchor =>

<a onClick="fomateName('Andrew D\'souza')"> <!-- this will alert "Andrew D'souza" -->

Escape the quote with backslashes.

<a onClick="fomateName('Andrew D\'souza')">
//this is not working ,because present of single quote

You can wrap it in double quotes like so:

   <a onClick="fomateName("Andrew D'souza")"> //this is not working ,because present of single quote

Never mind, just realized it already has double quotes, yeah use backslash for escape like so:

  <a onClick="fomateName('Andrew D\'souza')">

Try this. Use backslash - It will escape the quote breaks

<a onClick="fomateName('Andrew D\'souza')"> 

You can use escape character

<a onclick="formateName('AdrewD\'souza')">

You can escape the quote with a backslash..

fomateName('Andrew D\'souza');

This should work anyway:

var name = "Andrew D'souza";
fomateName(name);
发布评论

评论列表(0)

  1. 暂无评论