Reputation: 111
I have a string of text that I am trying to remove from a textarea in javascript. The text that I am trying to remove is in the following format:
Category:Attribute
Color:Green <- Example!
var catTitle = 'color';
var regexp = new RegExp(catTitle + '\:[.]*$', "g")
textarea.value = textarea.value.replace(regexp, "");
Since the attribute can be any length, I need my regular expression to go forward until the new line. I thought that [.]*$ would be acceptable to match any characters up to a new line; however, it doesn't seem to work.
Any help would be greatly appreciated.
Upvotes: 1
Views: 88
Reputation: 4105
Or, since you may have more lines:
var catTitle = 'Color';
var regexp = new RegExp(catTitle + ':.*', "g")
alert("skzxjclzxkc\nsasxasxColor:Red\nasdasdasd".replace(regexp, ""));
Upvotes: 0
Reputation:
.
inside a character class ([]
) matches itself -- it is no longer a wildcard. Also, regular expressions are case sensitive unless told otherwise ("i" flag) and :
(in that context) is not special so it does not need to be escaped.
[a-z]
or \w
might be good to use to match the Attribute, depending.
It might then go like:
var catTitle = "color"
var re = new RegExp(catTitle + ':[a-z]+$', "gi")
re.test("Color:Green") // true
re.test("color:Red") // true
re.test("color: Red") // false, put perhaps this should be accepted?
re.test("color:") // false
re.test("foo:bar") // false
I also changed the qualifier from *
to +
-- note the case of "color:" and how it's rejected. This will also reject colors in non-English alphabets.
Happy coding.
Upvotes: 2