简体   繁体   English

JavaScript中的正则表达式文本插入

[英]Regular Expression text insertion in javascript

I have some string that could be on a URL.. ala.. I can "get the name/value" etc.. that is not the issue. 我有一些可能在URL上的字符串.. ala ..我可以“获取名称/值”等。这不是问题。 The issue is that given some test I need to "insert" additional characters in the value. 问题是,经过一些测试,我需要在值中“插入”其他字符。 so: 所以:

var someValue = "yes_maybe_next_year"

If I get a string with "_maybe" in it, I would insert my additional chars after it, ala. 如果我得到一个带有“ _maybe”的字符串,我会在其后插入其他字符,ala。 so it would become: 因此它将变为:

var charsToInsert = "_no";
var someValue = "yes_maybe_next_year";
var newValue = "yes_maybe_no_next_year";

Here is the rub. 这是擦。 I might not get "maybe" in there. 我可能不会在那里。 So I need to insert "_no" after "yes". 所以我需要在“是”之后插入“ _no”。 Here is a second rub. 这是第二次尝试。 The string might contain chars that are different than "next_year". 该字符串可能包含与“ next_year”不同的字符。

var someValue = "yes_sometime_later";

So, in truth: I need to be able to insert via regex something like. 因此,实际上:我需要能够通过regex插入类似内容。

var regex = /^(yes_)(maybe_)(\w*)?/

I'm actually at a loss on how to do this. 实际上,我对如何执行此操作一无所知。

So, if "maybe_" exists, I'll put "no" after it, else "no" goes after "yes_". 因此,如果“ maybe_”存在,我将在其后加上“ no”,否则在“ yes_”之后加上“ no”。

Here is one possible solution: 这是一种可能的解决方案:

var newValue = someValue.replace(/yes_(maybe_)?/, "$&no_");

// "yes_maybe_next_year" --> "yes_maybe_no_next_year"
// "yes_sometime_later"  --> "yes_no_sometime_later"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM