简体   繁体   English

用 javascript 中的各种场景替换字符串的更好方法

[英]better way to replace string with various scenarios in javascript

How to replace special characters for different pattern of same string in javascript如何替换 javascript 中相同字符串的不同模式的特殊字符

am passing one string at a time and below are string patterns我一次传递一个字符串,下面是字符串模式

var str1="2456 #02-567"
var result = str1.replace(/#/g, '')

var str1="2-567 2456"
var result = str1.replace(/^/g, '0')
for these strings

2456 #02-567 , 2456 02-567, 2456 2-567,2456 #2-567

Expected Output 
2456 02-567 
 ===========
for these strings
#02-567 2456 , 2-567 2456, 02-567 2456, #2-567 2456

Expected Output 
02-567 2456

May be there is a clever solution, but this should work:可能有一个聪明的解决方案,但这应该有效:

 let str = ["2456 #02-567", "2456 02-567", "2456 2-567","2456 #2-567","#02-567 2456", "2-567 2456", "02-567 2456", "#2-567 2456","1234 12-345","1234 #12-345","#12-345 1234"]; //1234 12-345" or "1234 #12-345" or "#12-345 1234" for(let st of str) console.log(st.replace(/#?(\d)?(\d-)/g,replacer)) function replacer(match, p1, p2, offset, string){ let replaceSubString = p1 || "0"; replaceSubString += p2; return replaceSubString; }

I'm using a captouring group (expression in the parenthesis in the regular expression) that can be referenced in the second parameter of replace function with $1 (1 because is the first captouring group).我正在使用一个捕获组(正则表达式括号中的表达式),它可以在将 function replace$1的第二个参数中引用(1 因为是第一个捕获组)。 The ? ? instead point that the character is optional.而是指出该字符是可选的。

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

相关问题 有没有更好,更快的方法来用Javascript中的文本替换字符串中的数字? - Is there a better and faster way to replace digits in string by the text in Javascript? 用 JavaScript/jQuery 替换 dom 对象中字符串的各种出现的最快和健壮的方法 - Fastest and robust way to replace various occurencies of a string in dom objects with JavaScript/jQuery 在 Javascript 中提取字符串的更好方法 - Better way to extract a string in Javascript javascript - 更好的方法来逃避String.prototype.replace使用的字符串中的美元符号 - javascript - Better Way to Escape Dollar Signs in the String Used By String.prototype.replace 有没有更好的方法来链接 String#replace 方法? - Is there a better way to chain the String#replace method? 一种更好的方法,而不是在JavaScript中使用字符串替换 - A better approach instead of using String replace in javascript Javascript-有更好的方法来检查字符串而不是indexOf - Javascript - is there a better way to check an string instead of indexOf 将URL字符串传递到javascript文件的更好方法? - better way of passing URL string to javascript file? 有没有更好的方法在javascript中实现“字符串包含子字符串”? - Is there a better way to implement "string contains substring" in javascript? 在JavaScript中拆分日期字符串的更好方法是什么? - What is the better way to split Date string in JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM