Append string in before the last word Javascript

六眼飞鱼酱① 提交于 2021-02-05 12:31:14

问题


My input1 is "perfectly clean" "multi action" cleansing
My input2 is "perfectly clean" "multi action"

I need to append "and" in the last but one position eg: if input1 then output should be "perfectly clean" "multi action" and cleansing if input2 "perfectly clean" and "multi action"

The input is dynamic but I need the output with the double codes as in the input can u help me with a solution which satisfies both the input

i tried like this

var text = g_eCatalogMeta.searchCorrected,
    clength = text.split('"');

clength = clength.filter(function(n){ return n != "" && n!=" "});

if (clength.length >1) {
   var aa =clength.length;
   clength.insert(aa-1, "und");
   text = clength.join;
}

But could not get the double codes and the last word. Please help me out.


回答1:


The easiest way is a regular expression that inserts and before the last quoted string or the last word.

str.replace(/("[^"]+"|\w+)$/, "and $1");

https://regex101.com/r/yK5tD9/1

Regex breakdown:

(       = start of group 1 
"[^"]+" = quote, some non-quotes, quote
|       = OR
\w+     = a word
)       = end of group 1
$       = end of string

$1 in replacement means "whatever group 1 matches".



来源:https://stackoverflow.com/questions/27503893/append-string-in-before-the-last-word-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!