简体   繁体   English

如何在 javascript 中使用正则表达式替换字符串?

[英]How to replace string using regex in javascript?

How to check a string and replace the space into "_"?如何检查字符串并将空格替换为“_”?

let str = "hello @%123abc456:nokibul amin mezba jomadder% @%123abc456:nokibul% @%123abc456:nokibul amin mezba%"

str = str.replace(regex, 'something');

console.log(str);

// Output: str = "hello @%123abc456:nokibul_amin_mezba_jomadder% @%123abc456:nokibul% @%123abc456:nokibul_amin_mezba%"

Please help me out:)请帮帮我:)

Hint: You can use https://regex101.com/ to test whether a regex works, it supports substitution as well.提示:您可以使用https://regex101.com/来测试正则表达式是否有效,它也支持替换。

Regex being used: (\w+)[ ] , to grep all words between space, and use $1_ to substitute the space to underscore.使用的正则表达式: (\w+)[ ] ,到 grep 空格之间的所有单词,并使用$1_将空格替换为下划线。

 const regex = /(\w+)[ ]/gm; const str = `Input: str="nokibul" output: str="nokibul" Input: str="nokibul amin" Output: str="nokibul_amin" Input: str="nokibul amin mezba" Output: str="nokibul_amin_mezba" Input: str="nokibul amin mezba jomadder" Output: str="nokibul_amin_mezba_jomadder"`; const subst = `$1_`; // The substituted value will be contained in the result variable const result = str.replace(regex, subst); console.log('Substitution result: ', result);

Check this out.看一下这个。 I think it's gonna help我认为这会有所帮助
Hints:提示:

  1. /:(\w+\s*)+/g Separates the :nokibul amin mezba jomadder as a group. /:(\w+\s*)+/g:nokibul amin mezba jomadder为一个组。
  2. Replace the group with index-wise templating {0} , {1} ... {n} .用索引模板{0}{1} ... {n}替换组。
  3. Mapping the groups.映射组。 Ex: :nokibul amin mezba jomadder to :nokibul_amin_mezba_jomadder .例如: :nokibul amin mezba jomadder:nokibul_amin_mezba_jomadder
  4. Finally, replacing the templates {index} with groups.最后,将模板{index}替换为组。

 let str = "hello @%123abc456:nokibul amin mezba jomadder% @%123abc456:nokibul% @%123abc456:nokibul amin mezba%"; /* Extracting Groups */ let groups = str.match(/:(\w+\s*)+/g); /* Formatting Groups: Replacing Whitespaces with _ */ let userTags = groups.map((tag, index) => { /* Index wise string templating */ str = str.replace(tag, `{${index}}`) return tag.replace(/\s+/g, "_"); }); console.log(str); console.log(userTags); /* Replacing string templates with group values */ userTags.forEach((tag, index) => str = str.replace(`{${index}}`, tag)); console.log(str);

Simple one liner简单的一班轮

str.replace(/:[^%]*%/g, arg => arg.replace(/ /g, '_'))

Explanation:解释:

/:[^%]*%/g Find all occurrences starting with : and ending at % /:[^%]*%/g查找以:开头并以%结尾的所有匹配项

This will return patterns like this :nokibul amin mezba jomadder% :nokibul% :nokibul amin mezba%这将返回这样的模式:nokibul amin mezba jomadder% :nokibul% :nokibul amin mezba%

Next is to replace all space characters with underscores using this replace(/ /g, '_')接下来是使用这个replace(/ /g, '_')用下划线替换所有空格字符

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

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