Reputation: 5520
I have this in a javascript/jQuery string (This string is grabbed from an html ($('#shortcode')
) elements value which could be changed if user clicks some buttons)
[csvtohtml_create include_rows="1-10"
debug_mode="no" source_type="visualizer_plugin" path="map"
source_files="bundeslander_staple.csv" include cols="1,2,4" exclude cols="3"]
In a textbox (named incl_sc
) I have the value:
include cols="2,4"
I want to replace include_cols="1,2,4"
from the above string with the value from the textbox.
so basically:
How do I replace include_cols values here? (include_cols="2,4"
instead of include_cols="1,2,4"
) I'm great at many things but regex is not one of them. I guess regex is the thing to use here?
I'm trying this:
var s = $('#shortcode').html();
//I want to replace include cols="1,2,4" exclude cols="3"
//with include_cols="1,2" exclude_cols="3" for example
s.replace('/([include="])[^]*?\1/g', incl_sc.val() );
but I don't get any replacement at all (the string s is same string as $("#shortcode").html(). Obviously I'm doing something really dumb. Please help :-)
Upvotes: 0
Views: 93
Reputation: 80
In short what you will need is
s.replace(/include cols="[^"]+"/g, incl_sc.val());
There were a couple problems with your code,
To use a regex with String.prototype.replace
, you must pass a regex as the first argument, but you were actually passing a string.
This is a regex literal /regex/
while this isn't '/actually a string/'
In the text you supplied in your question include_cols
is written as include cols
(with a space)
And your regex was formed wrong. I recomend testing them in this website, where you can also learn more if you want.
The code above will replace the part include cols="1,2,3"
by whatever is in the textarea
, regardless of whats between the quotes (as long it doesn't contain another quote).
Upvotes: 1
Reputation: 336
First of all I think you need to remove the quotes and fix a little bit the regex.
const r = /(include_cols=\")(.*)(\")/g;
s.replace(r, `$1${incl_sc.val()}$3`)
Basically, I group the first and last part in order to include them at the end of the replacement. You can also avoid create the first and last group and put it literally in the last argument of the replace function, like this:
const r = /include_cols=\"(.*)\"/g;
s.replace(r, `include_cols="${incl_sc.val()}"`)
Upvotes: 1