Reputation: 21465
This question seems to be simple and repetitive here in SO.
But consider this string: SELECT a, b, c, d FROM
. I want to get only what is between SELECT
and FROM
.
Nice so I have found this answer that propose this regex: (?<=SELECT)(.*)(?=FROM)
. It's perfect if lookbehind works in JavaScript, according to this post:
Unlike lookaheads, JavaScript doesn't support regex lookbehind syntax
So it won't work(test it in regexpal that is made for JS). This anwser proposes this regex: SELECT=(.*?)FROM
. But it includes the two words, so it not fits my needs.
The purpose of this is to use in a replace
function to transform this...
SELECT a, b, c, d FROM
into this...
SELECT Count(*) FROM
Thank you in advance.
Upvotes: 2
Views: 7933
Reputation: 172418
Try this:-
$("button").click(function() {
var srctext = $("#fixme").text();
console.log("old text: " + srctext);
var newtext = srctext.replace(/(SELECT)(.+?)(?= FROM)/, "$1 count(*)");
console.log("new text: " + newtext);
$("#fixme").text(newtext)
});
WORKING JSFIDDLE:- http://jsfiddle.net/tkP74/1597/
Upvotes: 2
Reputation: 306
var query = "SELECT a, b, c, d FROM";
var iSelect = query.indexOf("SELECT");
var selLen = "SELECT".length;
var iFrom = query.indexOf("FROM");
if (iSelect >= 0 && iFrom >= 0) {
query = query.replace(query.substring(iSelect + selLen, iFrom), " COUNT(*) ");
console.log(query);
}
Upvotes: 1
Reputation: 214949
Just use a capturing group:
"SELECT a, b, c, d FROM".replace(/(SELECT)(.+?)(?= FROM)/, "$1 count(*)")
Upvotes: 7
Reputation: 72971
Just as an alternative to regular expressions for this specific string:
str = 'SELECT COUNT(*) ' + str.substr(str.indexOf('FROM'));
Upvotes: 1
Reputation: 71538
Well, you can just put the SELECT
back like I said in my comment:
str.replace(/SELECT (.*?)(?= FROM)/i, "SELECT Count(*)");
Upvotes: 1