Javascript Regex

Stephen Forlance
Stephen Forlance used Ask the Experts™
on
Hello all,
Im trying to create a function that would search through a string and then replace :something with '$something'

For example:
select * from internal where id = :id and name=:kn_op_id

would result in

select * from internal where id = '$id' and name='$kn_op_id'

Can anyone help?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016
Commented:
Hi,

pls try
var str   = 'select * from internal where id = :id and name=:kn_op_id';
var regex = /:\b(.+?)\b/;
str = str.replace(regex, "'\$$1'");
console.log(str);

Open in new window

REgards

Author

Commented:
Hi, for the first match its actually coming back as id = '$1' instead of $id
Commented:
result = subject.replace(/:(\w+)/g, "'$$$1'");


HTH,
Dan
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Why have you posted this to the JavaScript Topic Area - is there a JavaScript component to it - looks more like MySQL / PHP

Commented:
@Julian: that's plain SQL.
If the OP wants to modify SQL queries using JS, where is the problem?

Author

Commented:
Julian - its a javascript question regarding regex manipulation of a string.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
@Dan,

Just trying to establish what the background is - when you see an SQL query with $ variables (PHP) in a JavaScript context it raises questions - I was just making sure I completely understand the context before attempting a solution.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial