functi...">

How to remove duplicate character at end of line in regex

Can someone help me with the following regex

<script type="text/javascript">
        function quoteWords() {
            var search = document.getElementById("search_box");
            search.value = search.value.replace(/^\s*|\s*$/g, ""); //trim string of ending and beginning whitespace
            if(search.value.indexOf(" ") != -1){ //if more then one word
                search.value = search.value.replace(/^"*|"*$/g, "\"");
            }
        }
  </script>

<input type="text" name="keywords" value="" id="search_box" size="17">
<input onClick="quoteWords()" type="submit" value="Go">

Problem : it breaks when manually double quotes are added and press submit, at the end one additional double quote is entered. Regular expression code should see if double quotes exist, it should not add anything.

So it does "long enough"before "long enough""<- it adds an extra double quote at the end

Can anyone check the regex code to see how to solve this problem.

I want double quotes to be inserted once.

+3
source share
4 answers

There is a specific error in this line:

search.value = search.value.replace(/^"*|"*$/g, "\"");

, "* 0 . , , " + ", , , .

, - :

search.value = search.value.replace(/^"*|"*$/g, '')
search.value = '"' + search.value + '"'

, " " - " ", . , , , , . , , "" .

ECMAScript http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf 15.5.4.10 15.5.4.11 . , , .

, , -, :

http://www.grymoire.com/Unix/Sed.html#uh-6

sed, , * /g - . , JS , , . , "0 ".

+3

, ,

" "

- ( ). - ($). , , , 0 .

, :

search.value = (search.value + '"').replace(/^"*|"+$/g, "\"");
+3

* 0 , + . *, , 0 , \s, 0 " . * + , .

Edit: if you want the result to be surrounded by double quotes if they do not exist at the beginning or end of the line, use something like /^[^"]|[^"]$that reads like "the beginning of the line followed by any character other than the double quote or any character except for the double quote followed by the end of the line "

Double editing. It should probably be /^[^"\w]|[^"\w]$/that you don't replace the first and last characters of your match: /

+2
source

You can use +instead *:

search.value = search.value.replace(/^"+|"+$/g, '"');
+1
source

All Articles